1

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.

4

2 に答える 2

1

データスキーマをもう少しよく知っておくべきでした。私は、ライダーの ID ではなく、実際にはシリアル化された行 ID である間違った ID 列を操作しようとしていました。SQL の作業バージョン (MYSQL 上) は次のとおりです。

SELECT r.rider, rr.dated, rr.distance, i.firstname, i.lastname, sum(r.distance) 
FROM rides r
INNER JOIN (SELECT rider, distance, dated FROM rides ORDER BY dated DESC LIMIT 5) rr ON r.rider = rr.rider 
INNER JOIN riders i ON r.rider = i.id 
GROUP BY r.rider ORDER BY rr.dated DESC;

これは以下を返します:

+--------+---------------------+----------+-------- ---+----------------------+-----------------+
| | ライダー | 日付 | 距離 | ファーストネーム | 姓 | 合計 (r.距離) |
+--------+---------------------+----------+-------- ---+----------------------+-----------------+
| | 3304 | 2012-11-30 00:00:00 | 250 | ベンカテッシュ | ss | 250 |
| | 647 | 2012-11-22 00:00:00 | 31 | ラルフ | スエルズル | 22726 |
| | 2822 | 2012-11-21 00:00:00 | 15 | ウンベルト | カルデロン | 10421 |
| | 2339 | 2012-11-21 00:00:00 | 25 | ジュディ | ラッター | 8545 |
| | 1452年 | 2012-11-21 00:00:00 | 56 | フレッド | フレッド | スターリー | 64366 |
+--------+---------------------+----------+-------- ---+----------------------+-----------------+

回答ありがとうございます。

于 2012-12-18T01:32:32.550 に答える
0

このようなものは機能しますか?ところで、どのSQLサーバーが使用していますか?

SELECT sum(distance) 
FROM (SELECT distance FROM rides ORDER BY dated DESC LIMIT 5)
于 2012-12-15T00:31:00.377 に答える