This is an perplexing SQL problem (at least to me) involving GROUP BY
and AGGREGATES... would love any help.
Im working on a site that logs information about bike rides and riders. We have a table which contains a rider id, ride date, and ride distance. I want to display a table with the latest rides, and distances, as well as a total distance for each of those riders. Here is my sql and output (where id
is rider id):
+--------+---------------------+----------+ | id | dated | distance | +--------+---------------------+----------+ | 101240 | 2012-11-30 00:00:00 | 250 | | 101332 | 2012-11-22 00:00:00 | 31 | | 101313 | 2012-11-21 00:00:00 | 15 | | 101319 | 2012-11-21 00:00:00 | 25 | | 101320 | 2012-11-21 00:00:00 | 56 | +--------+---------------------+----------+
This is easy to get with:
SELECT id, dated, distance FROM rides ORDER BY dated LIMIT 5
What I can't seem to figure out is getting the riders cumulative total for these most recent rides... Basically:
SELECT sum(distance) FROM rides GROUP BY id
Is it possible to handle all this in SQL without having to do something programmatic? I've tried doing some subqueries and JOINS but to no avail yet!
Thanks in advance SO community.