SQL 按指定顺序排列

问题:

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
发布了42 篇原创文章 · 获赞 28 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/xiaoxiaoliluo917/article/details/103115747