175. 组合两个表
SQL架构
表1: Person
+-------------+---------+
| 列名 | 类型 |
+-------------+---------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+-------------+---------+
PersonId 是上表主键
表2: Address
+-------------+---------+
| 列名 | 类型 |
+-------------+---------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+-------------+---------+
AddressId 是上表主键
编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:
FirstName, LastName, City, State
code now
select FirstName, LastName, City, State from Person left join Address on Person.PersonId=Address.PersonId
join
按题意要求,使用outer join时可以保证指定表的每条记录都出现----即使没有匹配, outer join又可以分为left join, right join, full join。
我们想让Address表中即使没有Person,也让Person有Address属性,所以Address为必须出现表,那么我们可以用 Person表 left join Address,或者反过来用right join。
在join前先对Address表处理,去除Address里的重复项,然后让Person left join Address。在数据量特别大而且重复量也特别大时,可以节省join次数,从而节省效率,当然当数据量不那么大,重复数据不那么多时,反而会影响效率。

176. 第二高的薪水
SQL架构
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
code now
mysql:
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
where salary < (
SELECT MAX(Salary)
FROM Employee
)
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary;
SELECT
IFNULL(
(SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary;
oracle:
select max(salary) as SecondHighestSalary from (select salary,rownum rn from (select distinct salary from Employee order by salary desc)) where rn = 2
limit offset ifnull 嵌套
mysql里分页一般用limit来实现
1. select* from article LIMIT 1,3
2.select * from article LIMIT 3 OFFSET 1
上面两种写法都表示取2,3,4三条条数据
IFNULL(expression_1,expression_2);
如果expression_1不为NULL,则IFNULL函数返回expression_1; 否则返回expression_2的结果。
177. 第N高的薪水
编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200 |
+------------------------+
code now
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set n = N-1;
RETURN (
# Write your MySQL query statement below.
select ifnull(
(
select distinct Salary getNthHighestSalary
from Employee
order by Salary desc
limit n, 1
), null)
);
END
limit offset
**limit和offset用法
mysql里分页一般用limit来实现
- select* from article LIMIT 1,3
2.select * from article LIMIT 3 OFFSET 1
上面两种写法都表示取2,3,4三条条数据
当limit后面跟两个参数的时候,第一个数表示要跳过的数量,后一位表示要取的数量,例如
select* from article LIMIT 1,3 就是跳过1条数据,从第2条数据开始取,取3条数据,也就是取2,3,4三条数据
当 limit后面跟一个参数的时候,该参数表示要取的数据的数量
例如 select* from article LIMIT 3 表示直接取前三条数据,类似sqlserver里的top语法。
当 limit和offset组合使用的时候,limit后面只能有一个参数,表示要取的的数量,offset表示要跳过的数量 。
例如select * from article LIMIT 3 OFFSET 1 表示跳过1条数据,从第2条数据开始取,取3条数据,也就是取2,3,4三条数据
178. 分数排名
SQL架构
Create table If Not Exists Scores (Id int, Score DECIMAL(3,2))
Truncate table Scores
insert into Scores (Id, Score) values ('1', '3.5')
insert into Scores (Id, Score) values ('2', '3.65')
insert into Scores (Id, Score) values ('3', '4.0')
insert into Scores (Id, Score) values ('4', '3.85')
insert into Scores (Id, Score) values ('5', '4.0')
insert into Scores (Id, Score) values ('6', '3.65')
编写一个 SQL 查询来实现分数排名。
如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):
+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 'Rank'
code now
select Score, dense_rank() over (order by Score desc) as `Rank` from Scores;
rank() dense_rank()
窗口函数简介
MySQL从8.0开始支持开窗函数,这个功能在大多商业数据库中早已支持,也叫分析函数。
开窗函数与分组聚合比较像,分组聚合是通过制定字段将数据分成多份,每一份执行聚合函数,每份数据返回一条结果。
开窗函数也是通过指定字段将数据分成多份,也就是多个窗口,对每个窗口的每一行执行函数,每个窗口返回等行数的结果。
窗口函数分为静态窗口和滑动窗口,静态窗口的大小是固定的,滑动窗口的大小可以根据设置进行变化,在当前窗口下生成子窗口。
语法:
函数名([参数]) over(partition by [分组字段] order by [排序字段] asc/desc rows/range between 起始位置 and 结束位置)
函数解读:函数分为两个部分,第一部分是函数名称,开窗函数的数量较少,只有11个窗口函数+聚合函数(所有聚合函数都可以用作开窗函数),根据函数性质,有的要写参数,有的不需要写参数;
第二部分是over语句,over()是必须要写的,里面有三个参数,都是非必须参数,根据需求选写:
1.第一个参数是 partition by +分组字段,将数据根据此字段分成多份,如果不加partition by参数,那会把整个数据当做一个窗口。
2.第二个参数是 order by +排序字段,每个窗口的数据要不要进行排序。
3.第三个参数 rows/range between 起始位置 and 结束位置,这个参数仅针对滑动窗口函数有用,是在当前窗口下分出更小的子窗口。其中起始位置和结束位置可写:current row 边界是当前行,unbounded preceding 边界是分区中的第一行,unbounded following 边界是分区中的最后一行,expr preceding 边界是当前行减去expr的值,expr following 边界是当前行加上expr的值。rows是基于行数,range是基于值的大小,到讲解到滑动窗口函数时再详细介绍。
相同点:RANK()和DENSE_RANK()的是排名函数
不同点:RANK()是跳跃排序,即如果有两条记录重复,接下来是第三级别
如:1 2 2 4,会跳过3
DENSE_RANK()是连续排序,即如果有两条记录重复,接下来是第二级别
如:1 2 2 3
sqlzoon sqlzoon
select basics
1.Modify it to show the population of Germany
SELECT POPULATION FROM world WHERE NAME ='Germany'
2.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 quiz
SELECT from WORLD Tutorial
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
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 or population = 200000000
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
Show the name and population in millions for the countries of the continent ‘South America’. Divide the population by 1000000 to get population in millions.
select name , population/1000000 from world where continent='South America'
5.Show the name and population for France, Germany, Italy
select name,population from world where name in ('France','Germany','Italy')
Show the countries which have a name that includes the word ‘United’
select name from world where name like '%United%'
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.
Show the countries that are big by area or big by population. Show name, population and area.
select name,population,area from world where area >3000000 or population >250000000
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 be included.
Indonesia has a big population but a small area, it should be included.
China has a big population and big area, it should be excluded.
United Kingdom has a small population and a small area, it should be excluded.
select name,population,area from world where population >250000000 xor area >3000000
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) as population,round(gdp/1000000000,2) as gdp FROM world
WHERE continent='South America'
Show the name and 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
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)
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 function LEFT to isolate the first character.
You can use <> as the NOT EQUALS operator.
select name,capital from world where LEFT(name,1)=LEFT(capital,1) and name != capital
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'
Show the year and subject that won ‘Albert Einstein’ his prize.
select yr ,subject from nobel where winner ='Albert Einstein'
Give the name of the ‘Peace’ winners since the year 2000, including 2000.
select winner from nobel where yr >= 2000 and subject ='peace'
Show all details (yr, subject, winner) of the Literature prize winners for 1980 to 1989 inclusive.
select * from nobel where yr >= 1980 and yr <= 1989 and subject = 'Literature'
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'
)
Show the winners with first name John
select winner from nobel where winner like 'John%'
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)
Show the year, subject, and name of winners for 1980 excluding Chemistry and Medicine
select * from nobel where yr=1980 and subject not in ('Chemistry','Medicine')
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 * from nobel where (subject = 'Medicine' and yr < 1910 ) or (subject = 'Literature' and yr >= 2004 )
Find all details of the prize won by PETER GRÜNBERG
Non-ASCII characters
The u in his name has an umlaut. You may find this link useful https://en.wikipedia.org/wiki/%C3%9C#Keyboarding
select * from nobel where winner = 'PETER GRÜNBERG'
Find all details of the prize won by EUGENE O’NEILL
Escaping single quotes
You can’t put a single quote in a quote string directly. You can use two single quotes within a quoted string.
select * from nobel where winner = 'EUGENE O''NEILL'
Knights in order
List the winners, year and subject where the winner starts with Sir. Show the the most recent first, then by name order.
select winner,yr,subject from nobel where winner like 'Sir%' order by yr desc
The expression subject IN (‘Chemistry’,‘Physics’) can be used as a value - it will be 0 or 1.
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
List each country name where the population is larger than that of ‘Russia’.
SELECT name FROM world
WHERE population >
(SELECT population FROM world
WHERE name='Russia')
Show the countries in Europe with a per capita GDP greater than ‘United Kingdom’.
Per Capita GDP
The per capita GDP is the gdp/population
select name from world where continent = 'Europe' and gdp/population > (select gdp/population from world where name = 'United Kingdom')
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='Argentina' or name = 'Australia') order by name
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')
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.
The format should be Name, Percentage for example:
| name| percentage|
|Albania |3%|
|Andorra| 0%|
|Austria |11%|
Decimal places
Percent symbol %
select name , concat(round(population/(SELECT population FROM world WHERE name='Germany')*100, 0), '%') percentage from world where continent ='Europe'
Which countries have a GDP greater than every country in Europe? [Give the name only.] (Some countries may have NULL gdp values)
select name from world where gdp > all(select gdp from world where gdp>0 and continent = 'Europe')
Find the largest country (by area) in each continent, show the continent, the name and the area:
SELECT x.continent, x.name, x.area FROM world x
WHERE x.area >= ALL
(SELECT y.area FROM world y
WHERE y.continent=x.continent
AND y.area>0)
List each continent and the name of the country that comes first alphabetica
select continent,name
from world x
where x.name<=all(select name from world y where x.continent=y.continent)
order by x.continent
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.9.
select name,continent,population
from world as x
where 25000000>=all
(select population from world y where x.continent=y.continent)
Some countries have populations more than three times that of all of their neighbours (in the same continent). Give the countries and continents.
select x.name , x.continent
from world x
where population >= all(select 3*population from world y where x.continent = y.continent )
SUM and COUNT
Show the total population of the world.
SELECT SUM(population)
FROM world
List all the continents - just once each
select distinct continent from world
Give the total GDP of Africa
select sum(gdp) from world where continent = 'Africa'
How many countries have an area of at least 1000000
select count(distinct name) from world where area >=1000000
What is the total population of (‘Estonia’, ‘Latvia’, ‘Lithuania’)
select sum(population) from world where name in('Estonia','Latvia','Lithuania')
For each continent show the continent and number of countries.
select continent,count(name) from world group by continent
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
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 JOIN operation
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'
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
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'
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%'
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
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 dates of the matches and the name of the team in which ‘Fernando Santos’ was the team1 coach.
select mdate,teamname
from game,eteam
where game.team1=eteam.id and coach='Fernando Santos'
3379

被折叠的 条评论
为什么被折叠?



