带有组的SQL Order By子句

时间:2014-08-20 19:25:18

标签: sql sql-server sql-order-by

所以我有一个SELECT查询,结果如下:

SELECT .... 
ORDER BY SCORE, STUDENT_NUMBER

STUDENT_NAME    STUDENT_NUMBER    SCORE     
----------------------------------------
  Adam              9              69
  Bob              20              76
  Chris            10              77
  Dave             14              77
  Steve             5              80
  Mike             12              80

但我想通过STUDENT_NUMBER订购,但我希望它们按相同的分数分组:

STUDENT_NAME    STUDENT_NUMBER    SCORE     
----------------------------------------
  Steve             5              80
  Mike             12              80
  Adam              9              69
  Chris            10              77
  Dave             14              77
  Bob              20              76

所以现在数据是由STUDENT_NUMBER排序的,但如果有相同的SCORE,它们会被分组(就像它显示在下一行)。

是否可以使用ORDER BY子句执行此操作?

3 个答案:

答案 0 :(得分:4)

似乎订购也可以描述为按每个分数的最小学号排序。您可以使用窗口函数执行此操作。这是一个例子:

select <whatever>
from (select t.*, min(student_number) over (partition by score) as minsn
      from <whatever> t
     ) t
order by minsn, score, student_number asc;

您确实询问是否可以使用order by完成此操作。我认为答案是“是”,使用子查询。它看起来像这样:

select <whatever>
from <whatever> t
order by (select min(t2.student_number)
          from <whatever> t2
          where t2.score = t.score
         ),
         score, student_number;

答案 1 :(得分:1)

您可以按照该分数的最低学号编号,然后按学号编号:

SELECT STUDENT_NAME, STUDENT_NUMBER, SCORE 
FROM Scores s
ORDER BY (SELECT(MIN(STUDENT_NUMBER) FROM Scores WHERE SCORE = s.SCORE) ,
         STUDENT_NUMBER

答案 2 :(得分:1)

我相信这可以解决您的好奇订购要求。您可以在给定分数的最小Student_Number上订购,而不是在Student_Number上订购。

WITH v AS
(
    SELECT t1.Student_Number, t1.Score,
    (
        SELECT MIN(Student_Number) FROM table1
        WHERE Score = t1.Score
    ) AS MinStudentNumber
    FROM table1 t1
)
SELECT Student_Number, Score FROM v
ORDER BY MinStudentNumber, Score