查询第一名,第二名,第三名,并且每次在一行中使用第二名和第三名最低分

时间:2011-06-29 15:20:56

标签: mysql sql

我正试图通过ID获得前三名,如果有一个平局将第二和第三快的时间用作抢七局。所以在下面的例子中,3和5并列第三快,但3则是两者之间的第二快。

最好结果显示每个id的第1次,第2次和第3次,按第1次最快排序,然后按第2次排序,然后按第3次最快排序。

所以表格如下:

 ID | TIME
----|-------  
 1  |  6.45  
 2  |  12.43  
 1  |  4.52  
 4  |  16.24  
 5  |  9.43  
 2  |  10.46  
 2  |  8.46  
 3  |  17.49  
 4  |  20.46  
 3  |  16.49  
 5  |  16.97  
 3  |  9.43  
 1  |  25.77  

我正试图在一次查询中找到正确的结果。

所需的输出看起来像:

 ID | lowest time | 2nd lowest | 3rd lowest
----|-------------|------------|------------ 
 1  |  4.25       | 6.45       | 25.77  
 2  |  8.46       | 10.46      | 12.43  
 3  |  9.43       | 16.49      | 17.49
 5  |  9.43       | 16.97      |   

2 个答案:

答案 0 :(得分:5)

CREATE TABLE times  (ID int, theTime Decimal(5,2));

INSERT INTO times VALUES (1, 6.45),
(2, 12.43),  
(1, 4.52),
(4, 16.24),
(5, 9.43),
(2, 10.46),
(2, 8.46),
(3, 17.49),
(4, 20.46),
(3, 16.49),
(5, 16.97),
(3, 9.43),
(1, 25.77);


SELECT DISTINCT
    id,
    (SELECT thetime FROM times t2 WHERE t.iD = t2.id 
     order by thetime limit 1) lowesttime,
    (SELECT thetime FROM times t2 WHERE t.iD = t2.id 
     order by thetime limit 1,1) secondlowest,
    (SELECT thetime FROM times t2 WHERE t.iD = t2.id 
     order by thetime limit 2,1) thirdlowest
 FROM 
    times t
 ORDER BY
    lowesttime,
    secondlowest,
    thirdlowest
LIMIT 3   ; 



SELECT t1.id, 
       Min(t1.thetime) lowesttime, 
       Min(t2.thetime) secondlowest, 
       Min(t3.thetime) thirdlowest 
FROM   times t1 
       LEFT JOIN times t2 
         ON t1.id = t2.id 
            AND t1.thetime < t2.thetime 
       LEFT JOIN times t3 
         ON t2.id = t3.id 
            AND t2.thetime < t3.thetime 
GROUP  BY t1.id 
ORDER  BY lowesttime, 
          secondlowest, 
          thirdlowest 
LIMIT  3 ;

我认为第二个会更快,但我不确定,

请注意,如果ID 1看起来像这样

ID| Time
--------
1 | 4.52
1 | 4.52
1 | 25.77

然后对于第二个不正确的查询

,最终输出看起来像这样
ID | lowesttime | secondlowest | thirdlowest
-------------------------------------------
1  | 4.52       | 25.77        | null
2  |8.46        | 10.46        | 12.43
3  |9.43        | 16.49        | 17.49

答案 1 :(得分:0)

试试这个。它将适用于第一个平局值。如果您需要更多,则需要添加其他左连接并复制订单的第二部分。

这适用于SQL Server:

SELECT r1.ID, MIN(r1.time)
FROM #r r1
LEFT JOIN #r r2 
    on r1.Time = r2.Time
    AND r1.ID <> r2.ID
GROUP BY r1.id
ORDER BY MIN(r1.Time), MIN(CASE WHEN r2.time IS NULL THEN r1.time ELSE NULL END)