【SQL】sqlzoo练习题The nobel table can be used to practice more subquery.

蓝咒 提交于 2019-12-11 02:19:34

原地址:https://sqlzoo.net/wiki/The_nobel_table_can_be_used_to_practice_more_subquery./zh

上一篇:sqlzoo练习题SELECT within SELECT Tutorial

1.紅十字國際委員會 (International Committee of the Red Cross) 曾多次獲得和平獎。 試找出與紅十字國際委員會同年得獎的文學獎(Literature)得獎者和年份。
nobel(yr, subject, winner)

SELECT winner,yr FROM nobel
 where subject = 'Literature' and yr in
  (select yr from nobel
   where winner = 'International Committee of the Red Cross' and subject = 'Peace ')
--解题思路:因为获奖可能不止一次,所以年份可能不唯一。这里需要用in

2.日本物理學家益川敏英 (Toshihide Maskawa) 曾獲得物理獎。同年還有兩位日本人一同獲得物理獎。試列出這2位日本人的名稱。
nobel(yr, subject, winner)

select winner from nobel
 where yr in
  (select yr from nobel
   where winner = 'Toshihide Maskawa' ) and subject = 'Physics ' and winner != 'Toshihide Maskawa'
--解题思路:该物理学家同年获得物理奖奖的另外两个日本人,重点在同年,同样是物理奖。所以将这些条件依次满足即可拿到想要的数据。

3.首次頒發的經濟獎 (Economics)的得獎者是誰?
nobel(yr, subject, winner)

select winner from nobel x
 where yr <=
  all(select yr from nobel y
   where subject = 'Economics' and  x.subject = y.subject) and subject = 'Economics'
--解题思路:本题关键点在首次、经济奖、得奖者三者身上。需用用到自身连接子查询,查找到最早颁发的经济奖那一年的年份,再查找该年的奖项为经济奖即可得到结果。

4.哪幾年頒發了物理獎,但沒有頒發化學獎?
nobel(yr, subject, winner) 、

select distinct yr from nobel
 where subject = 'Physics' and yr not in
  (select yr from nobel
   where subject = 'Chemistry')
--解题思路:本题关键点在颁发了物理奖但没颁发化学奖的年份。某一年可能会颁发多个物理奖,所以需要年份去重。可以先查到颁发物理奖的年份,然后再查找这些年份里没有颁发化学奖的年份。后者需要用到子查询。

5.哪幾年的得獎者人數多於12人呢? 列出得獎人數多於12人的年份,獎項和得獎者。
nobel(yr,subject, winner)

select * from nobel
 where yr in
  (select yr from nobel
   group by yr having count(winner) > 12)
--解题思路:关键点在得奖人数多于12人的年份,条件肯定是查找年,但是可能不止一年里得奖人数超过12人,所以要用in。子查询里只需按照年份分组,然后计算出每组年份中的获奖者总和并筛选出大于12的就能拿到结果。

6.哪些得獎者獲獎多於1次呢?他們是哪一年獲得哪項獎項呢? 列出他們的名字,獲獎年份及獎項。先按名字,再按年份順序排序。
nobel(yr, subject, winner)

select winner,yr,subject from nobel
 where winner in
  (select winner from nobel
   group by winner having count(winner) >=2) order by winner,yr
--解题思路:本题关键点在于得奖者得奖次数多于1次,要找出这些人只需要按照获奖人分组,计算出获奖次数总和并筛选出大于1的即可。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!