sqlzoo练习

SELECT basics

1.The example uses a WHERE clause to show the population of 'France'. Note that strings (pieces of text that are data) should be in 'single quotes';

Modify it to show the population of Germany

SELECT population FROME world WHERE name = "Germany"

2.Checking a list The word IN allows us to check if an item is in a list. The example shows the name and population for the countries 'Brazil', 'Russia', 'India' and 'China'.

Show the name and the population for 'Sweden', 'Norway' and 'Denmark'.

SELECT name, population FROM world
WHERE name IN ('Sweden','Norway','Denmark');

3.Which countries are not too small and not too big? BETWEEN allows range checking (range specified is inclusive of boundary values). The example below shows countries with an area of 250,000-300,000 sq. km. Modify it to show the country and the area for countries with an area between 200,000 and 250,000.

SELECT name, area FROM world
WHERE area BETWEEN 200000 AND 250000

SELECT names

1.You can use WHERE name LIKE 'B%' to find the countries that start with "B".

  • The % is a_wild-card_it can match any characters

Find the country that start with Y

SELECT name FROM world
WHERE name LIKE 'Y%'

2.Find the countries that end withy

SELECT name FROM world
WHERE name LIKE '%Y'

3.Luxembourg has anx- so does one other country. List them both.

Find the countries that contain the letterx

SELECT name FROM world
WHERE name LIKE '%x%'

4.Iceland, Switzerland end withland- but are there others?

Find the countries that end withland

SELECT name FROM world
WHERE name LIKE '%land'

5.Columbia starts with aCand ends withia- there are two more like this.

Find the countries that start withCand end withia

SELECT name FROM world
WHERE name LIKE 'C%ia'

6.Greece has a doublee- who has a doubleo?

Find the country that hasooin the name

SELECT name FROM world
WHERE name LIKE '%oo%'

7.Bahamas has threea- who else?

Find the countries that have three or moreain the name

SELECT name FROM world
WHERE name LIKE "%a%a%a%"

8.India and Angola have an n as the second character. You can use the underscore as a single character wildcard.

SELECT name FROM world
WHERE name LIKE '_n%'
ORDER BY name

Find the countries that have "t" as the second character.

SELECT name FROM world
WHERE name LIKE '_t%'
ORDER BY name

9.Lesotho and Moldova both have two o characters separated by two other characters.

Find the countries that have two "o" characters separated by two others.

SELECT name FROM world
WHERE name LIKE '%o__o%'

10.Cuba and Togo have four characters names.

Find the countries that have exactly four characters.

SELECT name FROM world
WHERE name LIKE '____'

11.The capital of Luxembourg is Luxembourg. Show all the countries where the capital is the same as the name of the country

Find the country where the name is the capital city.

SELECT name
FROM world
WHERE name = capital

12.The capital of Mexico is Mexico City. Show all the countries where the capital has the country together with the word "City".

Find the country where the capital is the country plus "City".

SELECT name
FROM world
WHERE capital = concat(name," City")

13.Find the capital and the name where the capital includes the name of the country.

select capital,name from world
where capital like concat("%",name,"%")

14.Find the capital and the name where the capital is an extension of name of the country.

You should include Mexico City as it is longer than Mexico. You should not include Luxembourg as the capital is the same as the country.

select capital,name from world 
where capital like concat(name,"_%")

15.For Monaco-Ville the name is Monaco and the extension is -Ville.

Show the name and the extension where the capital is an extension of name of the country.

You can use the SQL function REPLACE.

SELECT name,replace(capital,name,'') FROM world
WHERE capital LIKE concat("%",name,"%") AND capital!=name

SELECT from WORLD Tutorial

1.Read the notes about this table.Observe the result of running this SQL command to show the name, continent and population of all countries.

SELECT name,continent,population FROM world

2.How to use WHERE to filter records.Show the name for the countries that have a population of at least 200 million. 200 million is 200000000, there are eight zeros.

SELECT name FROM world
WHERE population >= 200000000

3.Give the name and the per capita GDP for those countries with a population of at least 200 million.

select name,gdp/population from world
where population>=200000000

4.Show thenameandpopulationin millions for the countries of thecontinent'South America'. Divide the population by 1000000 to get population in millions.

select name,population/1000000 from world
where continent = 'South America'

5.Show thenameandpopulationfor France, Germany, Italy

select name,population from world
where name in ( 'France', 'Germany', 'Italy')

6.Show the countries which have anamethat includes the word 'United'

select name from world
where name like "%United%"

7.Two ways to be big: A country is big if it has an area of more than 3 million sq km or it has a population of more than 250 million.

select name,population,area from world
where area>3000000 or population>250000000

8.Exclusive OR (XOR). Show the countries that are big by area (more than 3 million) or big by population (more than 250 million) but not both. Show name, population and area.

  • Australia has a big area but a small population, it should beincluded.
  • Indonesia has a big population but a small area, it should beincluded.
  • China has a big populationandbig area, it should beexcluded.
  • United Kingdom has a small population and a small area, it should beexcluded.
select name,population,area from world
where (area>3000000 and population<250000000) or 
(area<3000000 and population>250000000)

9.Show the name and population in millions and the GDP in billions for the countries of the continent 'South America'. Use the ROUND function to show the values to two decimal places.

For South America show population in millions and GDP in billions both to 2 decimal places.

select name,round(population/1000000,2),round(gdp/1000000000,2) 
from world
where continent = "South America"

10.Show thenameand per-capita GDP for those countries with a GDP of at least one trillion (1000000000000; that is 12 zeros). Round this value to the nearest 1000.

Show per-capita GDP for the trillion dollar countries to the nearest $1000.

select name,round(gdp/population,-3) from world
where gdp >= 1000000000000

11.Greece has capital Athens.

Each of the strings 'Greece', and 'Athens' has 6 characters.

Show the name and capital where the name and the capital have the same number of characters.

  • You can use the LENGTH function to find the number of characters in a string
SELECT name,capital
FROM world
WHERE length(name)=length(capital)

12.The capital of Sweden is Stockholm. Both words start with the letter 'S'.

Show the name and the capital where the first letters of each match. Don't include countries where the name and the capital are the same word.

  • You can use the functionLEFTto isolate the first character.
  • You can use<>as theNOT EQUALSoperator.
SELECT name,capital
FROM world
where capital != name and left(capital,1) = left(name,1)

13.Equatorial Guinea and Dominican Republic have all of the vowels (a e i o u) in the name. They don't count because they have more than one word in the name.

Find the country that has all the vowels and no spaces in its name.

  • You can use the phrase name NOT LIKE '%a%' to exclude characters from your results.
  • The query shown misses countries like Bahamas and Belarus because they contain at least one 'a'
SELECT name
FROM world
WHERE name LIKE '%a%' 
and name LIKE '%e%'
and name LIKE '%i%'
and name LIKE '%o%'
and name LIKE '%u%'
AND name NOT LIKE '% %'

SELECT from Nobel Tutorial

1.Change the query shown so that it displays Nobel prizes for 1950.

SELECT yr, subject, winner
FROM nobel
WHERE yr = 1950

2.Show who won the 1962 prize for Literature.

SELECT winner
FROM nobel
WHERE yr = 1962
AND subject = 'Literature'

3.Show the year and subject that won 'Albert Einstein' his prize.

SELECT yr,subject
FROM nobel
WHERE winner = 'Albert Einstein'

4.Give the name of the 'Peace' winners since the year 2000, including 2000.

SELECT winner
FROM nobel
WHERE yr>=2000
AND subject = 'Peace'

5.Show all details (yr,subject,winner) of the Literature prize winners for 1980 to 1989 inclusive.

SELECT yr,subject,winner
FROM nobel
WHERE yr BETWEEN 1980 AND 1989
AND subject = 'Literature'

6.Show all details of the presidential winners:

  • Theodore Roosevelt
  • Woodrow Wilson
  • Jimmy Carter
  • Barack Obama
SELECT * FROM nobel
WHERE winner in ('Theodore Roosevelt',
                 'Woodrow Wilson',
                 'Jimmy Carter',
                 'Barack Obama')

7.Show the winners with first name John

SELECT winner
FROM nobel
WHERE winner LIKE "John%"

8.Show the year, subject, and name of Physics winners for 1980 together with the Chemistry winners for 1984.

SELECT yr,subject,winner
FROM nobel
WHERE (subject = 'Physics'
AND yr = 1980)
OR (subject = 'Chemistry'
AND yr = 1984)

9.Show the year, subject, and name of winners for 1980 excluding Chemistry and Medicine

SELECT yr,subject,winner
FROM nobel
WHERE yr=1980
AND subject not in ('Chemistry','Medicine')

10.Show year, subject, and name of people who won a 'Medicine' prize in an early year (before 1910, not including 1910) together with winners of a 'Literature' prize in a later year (after 2004, including 2004)

SELECT yr,subject,winner
FROM nobel
WHERE (yr<1910
AND subject = 'Medicine')
OR (yr>=2004
AND subject = 'Literature')

11.Find all details of the prize won by PETER GRÜNBERG

SELECT *
FROM nobel
WHERE winner = "PETER GRÜNBERG"

12.Find all details of the prize won by EUGENE O'NEILL

SELECT *
FROM nobel
WHERE winner = "EUGENE O'NEILL"

13.Knights in order

List the winners, year and subject where the winner starts withSir. Show the the most recent first, then by name order.

SELECT winner,yr,subject
FROM nobel
WHERE winner LIKE "Sir%"
ORDER BY yr DESC,winner

14.The expressionsubject IN ('Chemistry','Physics')can be used as a value - it will be0or1.

Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last.

SELECT winner,subject
FROM nobel
WHERE yr=1984
ORDER BY subject IN ('Physics','Chemistry'),subject,winner

SELECT within SELECT Tutorial

1.List each countrynamewhere thepopulationis larger than that of 'Russia'.

world(name, continent, area, population, gdp)
SELECT name FROM world
WHERE population >
(SELECT population FROM world
WHERE name='Russia')

2.Show the countries in Europe with a per capita GDP greater than 'United Kingdom'.

SELECT name FROM world 
WHERE gdp/population >
(SELECT gdp/population FROM world 
WHERE name = 'United Kingdom') 
AND continent = "Europe"

3.List the name and continent of countries in the continents containing either Argentina or Australia. Order by name of the country.

SELECT name,continent FROM world
WHERE continent IN
(SELECT continent FROM world 
WHERE name IN("Argentina","Australia"))
ORDER BY name

4.Which country has a population that is more than Canada but less than Poland? Show the name and the population.

SELECT name,population FROM world 
WHERE population>
(SELECT population FROM world 
WHERE name = "Canada")
AND population<
(SELECT population FROM world 
WHERE name = "Poland")

5.Germany (population 80 million) has the largest population of the countries in Europe. Austria (population 8.5 million) has 11% of the population of Germany.

Show the name and the population of each country in Europe. Show the population as a percentage of the population of Germany.

SELECT name,concat(round(population/
(SELECT population FROM world 
WHERE name = "Germany")*100,0),"%") 
FROM world
WHERE continent = "Europe"

6.Which countries have a GDP greater than every country in Europe? [Give thenameonly.] (Some countries may have NULL gdp values)

SELECT name FROM world
WHERE gdp >
(SELECT gdp from world 
WHERE continent = "Europe"
ORDER BY gdp DESC
LIMIT 1)

7.Find the largest country (by area) in each continent, show the continent, the name and the area:

SELECT continent, name,area FROM world x
WHERE area >= ALL
(SELECT area FROM world y
WHERE y.continent=x.continent)

8.List each continent and the name of the country that comes first alphabetically.

SELECT continent,name FROM world x
WHERE name = 
(SELECT name FROM world y 
WHERE x.continent = y.continent
ORDER BY name LIMIT 1)

9.Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name , continent and population.

SELECT name,continent,population FROM world 
WHERE continent IN
(SELECT continent FROM world x
WHERE
(SELECT population FROM world y
WHERE x.continent = y.continent
ORDER BY population DESC
LIMIT 1) <= 25000000)

10.Some countries have populations more than three times that of any of their neighbours (in the same continent). Give the countries and continents.

SELECT name,continent FROM world x 
WHERE population/3>= 
ALL(SELECT population FROM world y 
WHERE y.continent=x.continent 
AND population >0 
AND y.name!=x.name)

SUM and COUNT

1.Show the total population of the world.

SELECT SUM(population)
FROM world  

2.List all the continents - just once each.

SELECT distinct continent
FROM world

3.Give the total GDP of Africa

SELECT SUM(GDP)
FROM world
WHERE continent = "Africa"  

4.How many countries have an area of at least 1000000

SELECT COUNT(*)
FROM world
WHERE area>=1000000

5.What is the totalpopulationof ('Estonia', 'Latvia', 'Lithuania')

SELECT SUM(population)
FROM world
WHERE name in ('Estonia','Latvia','Lithuania')

6.For each continent show the continent and number of countries.

SELECT continent,count(name)
FROM world
GROUP BY continent

7.For each continent show the continent and number of countries with populations of at least 10 million.

SELECT continent,count(name)
FROM world
WHERE population>=10000000
GROUP BY continent

8.List the continents that have a total population of at least 100 million.

SELECT continent
FROM world
GROUP BY continent
HAVING SUM(population)>=100000000

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

1.Show the total number of prizes awarded.

SELECT COUNT(winner) FROM nobel

2.List each subject - just once

SELECT DISTINCT subject
FROM nobel 

3.Show the total number of prizes awarded for Physics.

SELECT COUNT(*)
FROM nobel
WHERE subject = "Physics"

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

SELECT subject,COUNT(*)
FROM nobel
GROUP BY subject 

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

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

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

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

7.Show the number of different winners for each subject.

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

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

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

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

SELECT yr
FROM nobel
WHERE subject = "Physics"
GROUP BY yr
HAVING COUNT(*) = 3

10.Show winners who have won more than once.

SELECT winner
FROM nobel
GROUP BY winner
HAVING COUNT(*) >1

11.Show winners who have won more than one subject.

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

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

SELECT yr,subject
FROM nobel
WHERE yr >= 2000
GROUP BY yr,subject
HAVING COUNT(*) = 3

The JOIN operation

1.The first example shows the goal scored by a player with the last name 'Bender'. The * says to list all the columns in the table - a shorter way of saying matchid, teamid, player, gtime

Modify it to show the_matchid_and_player_name for all goals scored by Germany. To identify German players, check for: teamid = 'GER'

SELECT matchid,player FROM goal 
WHERE teamid = 'GER'

2.From the previous query you can see that Lars Bender's scored a goal in game 1012. Now we want to know what teams were playing in that match.

Notice in the that the column matchid in the goal table corresponds to the id column in the game table. We can look up information about game 1012 by finding that row in the game table.

Show id, stadium, team1, team2 for just game 1012

SELECT id,stadium,team1,team2
FROM game
WHERE id = 1012

3.You can combine the two steps into a single query with a JOIN.

SELECT *
FROM game JOIN goal ON (id=matchid)

The FROM clause says to merge data from the goal table with that from the game table. The ON says how to figure out which rows in game go with which rows in goal the matchid from goal must match id from game. (If we wanted to be more clear/specific we could say
ON (game.id=goal.matchid)

The code below shows the player (from the goal) and stadium name (from the game table) for every goal scored.

Modify it to show the player, teamid, stadium and mdate for every German goal.

SELECT player, teamid, stadium,mdate
FROM game JOIN goal ON (id=matchid)
WHERE teamid = "GER"

4.Use the same JOIN as in the previous question.

Show the team1, team2 and player for every goal scored by a player called Mario player LIKE 'Mario%'

SELECT team1,team2,player
FROM game JOIN goal ON (id=matchid)
WHERE player LIKE "Mario%"

5.The table eteam gives details of every national team including the coach. You can JOIN`goal to eteam using the phrase goal JOIN eteam on teamid=id`

Show player, teamid, coach, gtime for all goals scored in the first 10 minutes gtime<=10

SELECT player, teamid,coach, gtime
FROM goal JOIN eteam on teamid = id
WHERE gtime<=10

6.To JOIN`game with eteam` you could use either
game JOIN eteam ON (team1=eteam.id) or game JOIN eteam ON (team2=eteam.id)

Notice that because id is a column name in both game and eteam you must specify eteam.id instead of just id

List the the dates of the matches and the name of the team in which 'Fernando Santos' was the team1 coach.

SELECT mdate,teamname
FROM game JOIN eteam on team1 = eteam.id
WHERE coach = "Fernando Santos"

7.List the player for every goal scored in a game where the stadium was 'National Stadium, Warsaw'

SELECT player
FROM game JOIN goal on matchid = id
WHERE stadium = 'National Stadium, Warsaw'

8.The example query shows all goals scored in the Germany-Greece quarterfinal.

Instead show thenameof all players who scored a goal against Germany.

SELECT distinct player
FROM game JOIN goal ON matchid = id 
WHERE (team1='GER' OR team2='GER')
AND teamid != 'GER'

9.Show teamname and the total number of goals scored.

SELECT teamname,COUNT(*)
FROM eteam JOIN goal ON id=teamid
GROUP BY teamname

10.Show the stadium and the number of goals scored in each stadium.

SELECT stadium,COUNT(*)
FROM game JOIN goal ON id=matchid
GROUP BY stadium

11.For every match involving 'POL', show the matchid, date and the number of goals scored.

SELECT matchid,mdate,count(*)
FROM game JOIN goal ON matchid = id 
WHERE (team1 = 'POL' OR team2 = 'POL')
GROUP BY matchid

12.For every match where 'GER' scored, show matchid, match date and the number of goals scored by 'GER'

SELECT matchid,mdate,count(*)
FROM game JOIN goal ON matchid = id 
WHERE teamid = 'GER'
GROUP BY matchid

~~13.List every match with the goals scored by each team as shown. This will use "CASE WHEN" which has not been explained in any previous exercises.
Notice in the query given every goal is listed. If it was a team1 goal then a 1 appears in score1, otherwise there is a 0. You could SUM this column to get a count of the goals scored by team1.Sort your result by mdate, matchid, team1 and team2.~~

SELECT mdate,
team1, SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) score1,
team2, SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) score2
FROM game LEFT JOIN goal ON id= matchid
GROUP BY mdate, team1, team2
ORDER BY mdate,matchid,team1,team2

More JOIN operations

1.List the films where the yr is 1962 [Showid,title]

SELECT id, title
FROM movie
WHERE yr=1962

2.Give year of 'Citizen Kane'.

SELECT yr
FROM movie
WHERE title = 'Citizen Kane'

3.List all of the Star Trek movies, include the id,title and yr (all of these movies include the words Star Trek in the title). Order results by year.

SELECT id,title,yr
FROM movie
WHERE title LIKE '%Star Trek%'
ORDER BY yr

4.What id number does the actor 'Glenn Close' have?

SELECT id
FROM actor
WHERE name = 'Glenn Close'

5.What is the id of the film 'Casablanca'

SELECT id
FROM movie
WHERE title = 'Casablanca'

6.Obtain the cast list for 'Casablanca'.

what is a cast list?

The cast list is the names of the actors who were in the movie.

Use movieid=11768, (or whatever value you got from the previous question)

SELECT name FROM actor
WHERE id IN
(SELECT actorid
FROM casting
WHERE movieid = (
SELECT id FROM movie
WHERE title = 'Casablanca'))

7.Obtain the cast list for the film 'Alien'

SELECT name FROM actor
WHERE id IN
(SELECT actorid
FROM casting
WHERE movieid = (
SELECT id FROM movie
WHERE title = 'Alien'))

8.List the films in which 'Harrison Ford' has appeared

SELECT title FROM movie
WHERE id in(
SELECT movieid FROM casting
WHERE actorid =
(SELECT id FROM actor
WHERE name = 'Harrison Ford'))

9.List the films where 'Harrison Ford' has appeared - but not in the starring role. [Note: theordfield of casting gives the position of the actor. If ord=1 then this actor is in the starring role]

    SELECT title FROM movie
    WHERE id in(
    SELECT movieid FROM casting
    WHERE actorid =
    (SELECT id FROM actor
    WHERE name = 'Harrison Ford') and ord !=1) 











你可能感兴趣的:(sql)