The nobel table can be used to practice more SUM and COUNT functions.

From SQLZoo
Jump to navigation Jump to search
Language:Project:Language policy English  • 日本語 • 中文

Nobel Prizes: Aggregate functions

This tutorial concerns aggregate functions such as COUNT, SUM and AVG.

Exercises

I am attempting an SQL tutorial, do not give me the complete answer, just a hint.
The table I am using has structure:

nobel(winner,subject,year)

The question is "{question}".
My attempt is "{attempt}"

Using MAX, AVG, DISTINCT and ORDER BY

Show the total number of prizes awarded.

SELECT COUNT(winner) FROM nobel
SELECT COUNT(winner) FROM nobel

List each subject - just once

SELECT DISTINCT subject FROM nobel

Show the total number of prizes awarded for Physics.

nobel(yr, subject, winner)  
SELECT COUNT(subject) FROM nobel
  WHERE subject='Physics'

Using GROUP BY and HAVING.

For each subject show the subject and the number of prizes.

nobel(yr,subject, winner)  
SELECT subject, COUNT(winner)
  FROM nobel
 GROUP BY subject

For each subject show the first year that the prize was awarded.

nobel(yr, subject, winner)  
SELECT subject, MIN(yr)
  FROM nobel
 GROUP BY subject

For each subject show the number of prizes awarded in the year 2000.

nobel(yr, subject, winner)  
SELECT subject,COUNT(yr)
FROM nobel
WHERE yr=2000
GROUP BY subject

Look into aggregates with DISTINCT.

Show the number of different winners for each subject. Be aware that Frederick Sanger has won the chemistry prize twice - he should only be counted once.

nobel(yr, subject, winner)  
SELECT subject,COUNT(DISTINCT winner)
FROM nobel
GROUP BY subject

For each subject show how many years have had prizes awarded.

nobel(yr, subject, winner)  
SELECT subject,COUNT(DISTINCT yr)
FROM nobel
GROUP BY subject

Using HAVING.

Show the years in which three prizes were given for Physics.

nobel(yr, subject, winner)  
SELECT yr
FROM nobel
WHERE subject='Physics'
GROUP BY yr
HAVING COUNT(winner)=3

Show winners who have won more than once.

nobel(yr, subject, winner)  
SELECT winner
FROM nobel
GROUP BY winner
HAVING COUNT(yr) > 1

Show winners who have won more than one subject.

nobel(yr, subject, winner)  
SELECT winner
FROM nobel
GROUP BY winner
HAVING COUNT(DISTINCT subject)>1

GROUP BY yr, subject

Show the year and subject where 3 prizes were given. Show only years 2000 onwards.

nobel(yr, subject, winner)  
SELECT yr,subject
FROM nobel
WHERE yr>=2000
GROUP BY yr,subject
HAVING COUNT(winner)=3
DataWars, Data Science Practice Projects - LogoDataWars: Practice Data Science/Analysis with +100 Real Life Projects