问题:
table-------nobel(yr, subject, winner)
找1984年的获奖者(winner),按照获奖项目(subject)升序排列,获奖项目一样的,按照获奖者升序排列,并且当获奖项目是Chemistry和Physics的放在后面,并升序排列。
(该问题来源–学SQL语句特别好的网站sqlzoo:SELECT from Nobel Tutorial)
查询语句:
- 解法1:
select winner, subject
from nobel
where yr=1984
order by CASE WHEN subject IN ('Chemistry','Physics') THEN 1
ELSE 0 END,
subject,winner
case when 的语法可以参考CASE WHEN
- 解法2:
(SELECT winner,subject
FROM nobel where yr=1984 AND subject NOT IN ('Chemistry','Physics')
order by subject, winner limit 99999)
UNION
(select winner,subject from nobel
where yr=1984 AND subject IN ('Chemistry','Physics')
order by subject, winner limit 999999)
关于解法2 Limit 99999这一句必不可少,如果不写它,UNION以后排序的结果就变了。
UNION的用法可以参见:SQL UNION 和 UNION ALL 操作符
- 解法3:
select winner, subject
from nobel
where yr=1984
order by subject IN ('Chemistry','Physics'),subject,winner