http://zh.sqlzoo.net/wiki/The_nobel_table_can_be_used_to_practice_more_SUM_and_COUNT_functions./zh
nobel( yr,subject, winner)?
Chemistry 化學(xué)獎(jiǎng)
Economics 經(jīng)濟(jì)獎(jiǎng)
Literature 文學(xué)獎(jiǎng)
Medicine 醫(yī)學(xué)獎(jiǎng)
Peace 和平獎(jiǎng)
Physics 物理獎(jiǎng)
1.
找出總共有多少個(gè)獎(jiǎng)?lì)C發(fā)了。
Selectcount(subject) from nobel
2.
列出每一個(gè)獎(jiǎng)項(xiàng)(subject),只列一次
Select distinct(subject)from nobel
3.
找出物理獎(jiǎng)的總頒發(fā)次數(shù)。
Select count(subject)from nobel
Where subject=’Physics’
4.
對(duì)每一個(gè)獎(jiǎng)項(xiàng)(Subject),列出頒發(fā)數(shù)目。
Selectsubject,count(subject) from nobel
GROUP BY subject
5.
對(duì)每一個(gè)獎(jiǎng)項(xiàng)(Subject),列出首次頒發(fā)的年份。
Selectsubject,min(yr) from nobel
group by subject
Order by yr
說明:使用最小函數(shù)min()計(jì)算首次頒獎(jiǎng)的年份。年份最小則為第一次最早時(shí)間。
6.
對(duì)每一個(gè)獎(jiǎng)項(xiàng)(Subject),列出2000年頒發(fā)的數(shù)目。
SELECTsubject,COUNT(SUBJECT) from nobel
WHERE YR=2000
Group by subject
7.
對(duì)每一個(gè)獎(jiǎng)項(xiàng)(Subject),列出有多少個(gè)不同的得獎(jiǎng)?wù)摺?/p>
selectsubject,count(distinct(winner)) from nobel
group by subject
說明:原題意需要求出多少個(gè)不同的得獎(jiǎng)?wù)摺?jì)數(shù)人數(shù),且不重復(fù)。所以疊加使用技術(shù)函數(shù)和去重函數(shù)“count(distinct())”,注意雙括號(hào)必須齊全。
8.
對(duì)每一個(gè)獎(jiǎng)項(xiàng)(Subject),列出有多少年曾頒發(fā)過。
select subject, count(distinct(yr))from nobel
group by subject
說明:此處需要注意“有多少年”不光要計(jì)數(shù)還要去重,所以疊加使用計(jì)數(shù)函數(shù)和去重函數(shù)“count(distinct()) ”
9.
列出哪年曾同年有3個(gè)物理獎(jiǎng)Physics得獎(jiǎng)?wù)摺?/p>
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
說明:先按照年份分組得出每一年獲獎(jiǎng)的人數(shù),同時(shí)加上過濾條件subject='Physics'即得出每一年獲得物理獎(jiǎng)的人數(shù)。
在分組的基礎(chǔ)上設(shè)置過濾條件人數(shù)為3人,使用條件語(yǔ)句having count(winner)=3。
10.
列出誰(shuí)得獎(jiǎng)多於一次。
select winner,count(winner)
from nobel
group by winner
having count(winner)>1
說明:首先按照姓名分類,得出每個(gè)人都獲得了多少獎(jiǎng),然后將獲獎(jiǎng)次數(shù)大于1的挑選出來,使用條件語(yǔ)句having count(winner)>1。Count(winner)用于計(jì)算每一個(gè)獲獎(jiǎng)人的獲獎(jiǎng)次數(shù)。
11.
列出誰(shuí)獲得多於一個(gè)獎(jiǎng)項(xiàng)(Subject)
說明:先求出每個(gè)人都獲得過哪些獎(jiǎng),即按照獲獎(jiǎng)人winner分組。然后對(duì)獎(jiǎng)項(xiàng)進(jìn)行計(jì)數(shù),篩選出數(shù)字大于1的結(jié)果。注意:必須先對(duì)獎(jiǎng)項(xiàng)去重,然后再計(jì)數(shù),需要得出獎(jiǎng)項(xiàng)類別大于1。
Select WINNER,count(subject)
From nobel
Group by winner
Having COUNT(distinct(SUBJECT))>1
12.
哪年哪獎(jiǎng)項(xiàng),是同一獎(jiǎng)項(xiàng)(subject)頒發(fā)給3個(gè)人。只列出2000年及之後的資料。
nobel(yr, subject,winner)?
select yr,subject
???from nobel
???where yr>=2000
???group by yr,subject
???having? count(subject)=3