in reply to Help with manipulating data from a database??

If I understand correctly, you want the minimum distance (along with the stop_reference) for each service_id. If you didn't need the stop_reference, you could just do a GROUP BY:

-- not what you want SELECT service_id, min(distance) FROM table GROUP BY service_id;

But then you lose the stop_reference information, because you've "grouped" that away.

So what I'd probably do is use ORDER BY:

SELECT stop_reference, service_id, distance FROM table ORDER BY service_id, distance;

Then you just print out (or store) every time the service_id changes:

my $last_service_id = -8675309; # for a good time, call while ($sth->fetch()) { if ($service != $last_service_id) { print "min dist for service '$service' = '$distance' at stop ' +$stops'\n"; $last_service_id = $service; } }

Replies are listed 'Best First'.
Re^2: Help with manipulating data from a database??
by dsheroh (Monsignor) on Jul 02, 2007 at 15:38 UTC
    Ummm... You know you can GROUP BY multiple fields, right?
    SELECT stop_reference, service_id, min(distance) FROM table GROUP BY stop_reference, service_id ;
    The basic rule is that you can include as many fields in a summary query as you like, provided that each one of them has either a summary operation (such as min()) or a GROUP BY applied to it. (This does rule out anything like SELECT * without going to a subquery, but, then, I only use SELECT * when I'm querying by hand anyhow. Using it in my code carries too much risk of breakage if the table's columns get reordered.)
      I thought about the double GROUP BY, but I think that'd only work if stop_reference is an ID-like column, with distinct values, right? I was assuming that since stop_reference is referring to bus stops, that the same stop_reference might occur more than once (for example where two or more bus lines intersect). In that case, I think the GROUP BY would no longer work because you'd "group away" some extra rows, right?
Re^2: Help with manipulating data from a database??
by Harch84 (Acolyte) on Jul 02, 2007 at 15:17 UTC
    That is exactly the answer I was looking for thanks so much to everyone for their advice and help and especially to ForgotPasswordAgain for his answer :-) You guys really are Perl legends!! Some day ill hope to repay you with some knowledge of my own!