SQLZOOL练习题答案和解析 第9- 关 Window functions

– 第9- 关 Window functions - SQLZOO


-- 练习窗口函数

--1. Show the lastName, party and votes for the constituency 'S14000024' in 2017.
-- 练习where 

select lastName, party, votes 
from ge 
where constituency = 'S14000024' and yr = 2017
order by votes desc 


-- 2. Show the party and RANK for constituency S14000024 in 2017. List the output by party
-- 练习 rank 

select party
,votes 
, rank() over(order by votes desc) as posn 
from ge 
where constituency = 'S14000024' and yr = 2017
order by party

-- 3. Use PARTITION to show the ranking of each party in S14000021 in each year. Include yr, party, votes and ranking (the party with the most votes is 1).
-- 练习分区 partition
select yr
, party
, votes
, rank() over(partition by yr order by votes desc) as posn  
from ge 
where constituency = 'S14000021'
order by party,yr 

-- 4. Use PARTITION BY constituency to show the ranking of each party in Edinburgh in 2017. Order your results so the winners are shown first, then ordered by constituency.

-- 提示:Edinburgh 就是区域在'S14000021' and 'S14000026'。

select constituency, party, votes,
rank() over (partition by constituency order by votes desc) as posn 
from ge 
where constituency between 'S14000021' and 'S14000026'
and yr = 2017
order by posn, constituency


-- 5.Show the parties that won for each Edinburgh constituency in 2017.
-- 练习子查询

select constituency,party
from (select constituency, party, votes,
rank() over (partition by constituency order by votes desc) as posn 
from ge 
where constituency between 'S14000021' and 'S14000026'
and yr = 2017
order by posn, constituency) as rk 
where rk.posn =1

-- 6. Show how many seats for each party in Scotland in 2017.
-- 注意 Scottish constituencies start with 'S'

select party,count(party)
from (select constituency, party, votes,
rank() over (partition by constituency order by votes desc) as posn 
from ge 
where constituency like 'S%'
and yr = 2017
order by posn, constituency) as rk 
where rk.posn =1
group by party 


-- 方法2 
select party,count(*) 
from (
select constituency,party, votes,
rank() over (partition by constituency order by votes desc) as posn
from ge
where constituency like 'S%'
and yr  = 2017) rk
where rk.posn=1
group by rk.party
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值