SQL - GROUP BY和ORDER BY MIN

时间:2018-03-05 08:41:46

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

我有玩家结果表:

id | id_user | timems | status | cancel

玩家在两种状态之间进行选择:开始游戏时为1或2。我列出了最佳时间排名:

SELECT *, MIN(timems) AS besttime 
FROM `wyniki` 
WHERE NOT cancel=1 
GROUP BY id_user 
ORDER BY MIN(timems) ASC

这很好,但我不知道'状态'的'最佳时间'是什么。

2 个答案:

答案 0 :(得分:1)

此查询容易出错

你可以这样做

SQL查询:

SELECT id_user, status , MIN(timems) AS besttime FROM `wyniki` 
WHERE NOT cancel=1 GROUP BY id_user, status ORDER BY MIN(timems) ASC

答案 1 :(得分:0)

SELECT id_user, 
       MIN(case when status = 1 then timems else null end) AS best_time_1,
       MIN(case when status = 2 then timems else null end) AS best_time_2
FROM wyniki 
WHERE cancel <> 1 
GROUP BY id_user 
ORDER BY MIN(timems) ASC