使用group by和order by时获得最低值

时间:2015-04-08 04:36:14

标签: mysql sql group-by sql-order-by

我有一个看起来有大约50行的表。该表保存了赛道会议的结果。结构如下:

Table Structure

我正在做的是为每个活动获得前十名。以下是我到目前为止的情况:

SELECT * FROM Times WHERE event='1600m' GROUP BY fname, lname ORDER BY time, event LIMIT 10

每个人每个活动都可以列入一次。这是有效的,但如果你看看下面1600米的所有时间......

all 1600m results

您可以看到Kyle Rummens的时间为4:32:00。下图是上面sql语句的结果:

sql statement result

凯尔的时间是4:36:00

我怎样才能让它成为1600米event前10个最快时间的列表,每个人只能在列表上一次,这是每个人最快的时间

编辑:我被要求在文字中添加我的结果而不是图像,所以这里是:

这是上述查询的结果:

fname  lname       event time     meetName             date
====== =========== ===== ======== ==================== ==========
Jeron  Tucker      1600m 04:09:00 Coaches Meet         2015-02-12
Chris  Hughes      1600m 04:27:00 Distance Chalenge    2015-02-10
Andrew Rummens     1600m 04:28:00 Simplot Games        2015-02-20
Kyle   Rummens     1600m 04:36:00 Simplot Games        2015-02-19
Alex   Southerland 1600m 04:52:00 Coaches Meet         2015-02-12
Canyon Schmerse    1600m 04:54:00 Arcadia Invitational 2015-05-12
Joseph Stone       1600m 05:08:00 Coaches Meet         2015-02-12
Teron  Tucker      1600m 05:09:00 Harvard Track Meet   2015-02-19
Little Jacob       1600m 05:12:00 Arcadia Invitational 2015-05-12
Connor Kleinman    1600m 05:54:00 BYU Invitational     2015-04-03

3 个答案:

答案 0 :(得分:3)

使用min(time)让每位游泳运动员找到每位游泳运动员最快的时间:

SELECT fname, lname, min(time) as tune
FROM Times
WHERE event = '1600m'
GROUP BY fname, lname
ORDER BY time
LIMIT 10

无需按event订购,因为它始终是'1600m'

答案 1 :(得分:0)

使用相关子查询:

SELECT t1.* 
FROM Times t1
WHERE t1.event='1600m' AND t1.time = (SELECT MAX(time)
                                      FROM Times t2
                                      WHERE t2.event='1600m' AND
                                            t1.fname = t2.fname AND
                                            t1.lname = t2.fname)
ORDER BY t1.time
LIMIT 10;

答案 2 :(得分:-2)

在SELECT

之后添加单词DISTINCT
SELECT DISTINCT * FROM Times WHERE event='1600m' GROUP BY fname, lname ORDER BY MIN(time) LIMIT 10