SQL复杂查询 - 同一查询中的ORDER BY和GROUP BY无法正常工作

时间:2017-06-06 07:59:39

标签: sql sql-server

我有一张这样的桌子, enter image description here

现在,我想找出胜利者,他们在早期给出了最正确的答案。我尝试过类似的东西,

{{1}}

输出是 - enter image description here

现在,当我尝试ORDER BY creation_time时,它没有给出预期但是错误。找出胜利者的查询应该是什么。

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT COUNT(is_correct), msisdn , min(creation_time) as min_creation
FROM [robi_contest].[dbo].[tbl_quiz_reply] 
WHERE is_correct = 1 group by msisdn
order by min_creation

问题是您没有将列作为组的一部分返回。对列应用min()允许您按照第一次出现的顺序进行排序。

答案 1 :(得分:1)

试试这个

SELECT COUNT(is_correct), msisdn 
FROM [robi_contest].[dbo].[tbl_quiz_reply] 
WHERE is_correct = 1 
group by msisdn 
order by max(msisdn) or Min(msisdn)

尝试按Max或min排序您想要的

答案 2 :(得分:0)

SELECT COUNT(is_correct), msisdn 
FROM (SELECT * FROM tbl_quiz_reply WHERE is_correct = 1 ORDER BY creation_time DESC) as test
group by msisdn

答案 3 :(得分:0)

我认为这就是你需要的

SELECT TOP (1) WITH TIES
       msisdn , COUNT(is_correct) AS NumberOfCorrectAnswers,
       max(creation_time) AS LastCorrectAnswerDatetime
FROM [robi_contest].[dbo].[tbl_quiz_reply] 
WHERE is_correct = 1 
GROUP BY msisdn
ORDER BY COUNT(is_correct) DESC, max(creation_time) ASC