The nobel table can be used to practice more SUM and COUNTfunctions./zh2018-04-18

http://zh.sqlzoo.net/wiki/The_nobel_table_can_be_used_to_practice_more_SUM_and_COUNT_functions./zh

nobel( yr,subject, winner) 

Chemistry 化學獎

Economics 經濟獎

Literature 文學獎

Medicine 醫學獎

Peace 和平獎

Physics 物理獎


1.

找出總共有多少個獎頒發了。

Selectcount(subject) from nobel


2.

列出每一個獎項(subject),只列一次

Select distinct(subject)from nobel


3.

找出物理獎的總頒發次數。

Select count(subject)from nobel

Where subject=’Physics’


4.

對每一個獎項(Subject),列出頒發數目。

Selectsubject,count(subject) from nobel

GROUP BY subject


5.

對每一個獎項(Subject),列出首次頒發的年份。

Selectsubject,min(yr) from nobel

group by subject

Order by yr

说明:使用最小函数min()计算首次颁奖的年份。年份最小则为第一次最早时间。


6.

對每一個獎項(Subject),列出2000年頒發的數目。


SELECTsubject,COUNT(SUBJECT) from nobel

WHERE YR=2000

Group by subject


7.

對每一個獎項(Subject),列出有多少個不同的得獎者。

selectsubject,count(distinct(winner)) from nobel

group by subject


说明:原题意需要求出多少个不同的得奖者——计数人数,且不重复。所以叠加使用技术函数和去重函数“count(distinct())”,注意双括号必须齐全。


8.

對每一個獎項(Subject),列出有多少年曾頒發過。


select subject, count(distinct(yr))from nobel

group by subject

说明:此处需要注意“有多少年”不光要计数还要去重,所以叠加使用计数函数和去重函数“count(distinct())


9.

列出哪年曾同年有3個物理獎Physics得獎者。

selectyr,count(winner) from nobel

wheresubject='Physics'

group by yr

having count(winner)=3

或者select yr fromnobel

wheresubject='Physics'

group by yr

having count(winner)=3


说明:先按照年份分组得出每一年获奖的人数,同时加上过滤条件subject='Physics'即得出每一年获得物理奖的人数。

在分组的基础上设置过滤条件人数为3人,使用条件语句having count(winner)=3。



10.

列出誰得獎多於一次。

select winner,count(winner)

from nobel

group by winner

having count(winner)>1

说明:首先按照姓名分类,得出每个人都获得了多少奖,然后将获奖次数大于1的挑选出来,使用条件语句having count(winner)>1。Count(winner)用于计算每一个获奖人的获奖次数。




11.

列出誰獲得多於一個獎項(Subject)


说明:先求出每个人都获得过哪些奖,即按照获奖人winner分组。然后对奖项进行计数,筛选出数字大于1的结果。注意:必须先对奖项去重,然后再计数,需要得出奖项类别大于1。


Select WINNER,count(subject)

From nobel

Group by winner

Having COUNT(distinct(SUBJECT))>1



12.

哪年哪獎項,是同一獎項(subject)頒發給3個人。只列出2000年及之後的資料。

nobel(yr, subject,winner) 


select yr,subject

   from nobel

   where yr>=2000

   group by yr,subject

   having  count(subject)=3

你可能感兴趣的:(The nobel table can be used to practice more SUM and COUNTfunctions./zh2018-04-18)