我正在学习SQL。
我的表中有这些记录:
STUDENT_NAME STATUS CLASS_ID ORDERING
----------------------------------------------
Adam 'FR' 10 1
Conan 'SE' 3 5
Chris 'SE' 4 8
Louis 'JR' null 10
Dave 'JR' 14 17
Alice 'SO' 14 8
Paul 'SE' 4 6
Tom 'SO' null 3
Eric 'FR' 14 5
Blake 'JR' 11 2
Ryan 'SE' 3 13
Matt 'FR' null 22
我希望通过ORDERING 订购,但我希望按其状态分组(就像具有相同状态的值一样)。
例如,结果如下所示:
STUDENT_NAME STATUS CLASS_ID ORDERING
----------------------------------------------
Adam 'FR' 10 1
Eric 'FR' 14 5
Matt 'FR' null 22
Blake 'JR' 11 2
Louis 'JR' null 10
Dave 'JR' 14 17
Tom 'SO' null 3
Alice 'SO' 14 8
Conan 'SE' 3 5 // SAME CLASS_ID
Ryan 'SE' 3 13
Paul 'SE' 4 6 // SAME CLASS_ID
Chris 'SE' 4 8
Adam拥有最低的ORDERING值,因此他排名第一。但他的状态是' FR'所以下一个学生将是Eric,他的ORDERING低于Matt。
额外条件: 如果CLASS_ID不为null,我想根据CLASS_ID对其进行分组
是否可以通过条款' SELECT' ...' ORDER BY'来获得结果(请说是!)
我使用此查询,但效果不佳:
SELECT ... FROM STUDENTS stu
ORDER BY
(SELECT MIN(S.ORDERING) FROM STUDENTS S WHERE S.STATUS = 'FR' AND stu.STATUS = 'FR'),
(SELECT MIN(S.CLASS_ID) FROM STUDENTS S WHERE S.CLASS_ID = stu.CLASS_ID),
stu.CLASS_ID ASC,
stu.ORDERING ASC
我也可以使用CASE子句。我需要你的帮助!
答案 0 :(得分:2)
试试这个。我为MySQL写了这个,它也适用于SQL Server。它将NULL CLASS_IDS组合在一起(如果有的话)。我不会想到另一种方法。它给出了您正在寻找的结果。
SELECT stu.*
FROM STUDENTS stu
ORDER BY
(SELECT MIN(S.ORDERING) FROM STUDENTS S WHERE S.STATUS = stu.STATUS),
(SELECT MIN(S.ORDERING) FROM STUDENTS S WHERE S.STATUS = stu.STATUS AND IFNULL(S.CLASS_ID, '') = IFNULL(stu.CLASS_ID, '')),
stu.ORDERING
SQL小提琴:sqlfiddle.com/#!2/a5a10/10/0
答案 1 :(得分:2)
答案 2 :(得分:1)
听起来你想按每组最小的顺序排序
select s.* from students s
join (
select status, min(ordering) min_status_ordering
from students group by status
) t1 on t1.status = s.status
join (
select class_id, status, min(ordering) min_class_ordering
from students group by status, class_id
) t2 on (t2.class_id = s.class_id
or (t2.class_id is null and s.class_id is null))
and t2.status = s.status
order by t1.min_status_ordering, t2.min_class_ordering, s.ordering, s.status, s.class_id