SQLZOO_Window functions

       感觉窗口函数是sqlzoo里比较难的一块,于是写下这篇文章,共同学习。

这块的题目不在sqlzoo主页的左侧栏目,而是在下方,我也是刷完左侧题目后面才发现的。由于sql代码很容易懂,就不做过多解释了,详见代码。

1、Warming up
Show the lastName, party and votes for the constituency ‘S14000024’ in 2017.

SELECT lastName, party, votes
FROM ge
WHERE constituency = 's14000024' AND yr = 2017
ORDER BY votes DESC

2、Who won?
Show the party and RANK for constituency S14000024 in 2017. List the output by party

SELECT 
party
,votes
,RANK() OVER (ORDER BY votes DESC) as posn
FROM ge
WHERE constituency = 'S14000024' AND yr = 2017
ORDER BY party

3、PARTITION BY
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).

SELECT 
yr
,party
,votes
,RANK() OVER (PARTITION BY yr ORDER BY votes DESC) posn
FROM ge
WHERE constituency = 'S14000021'
ORDER BY party,yr

4、Edinburgh Constituency
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.

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、Winners Only
Show the parties that won for each Edinburgh constituency in 2017.

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

6、Scottish seats
Show how many seats for each party in Scotland in 2017.

SELECT party,COUNT(*) 
FROM 
(
	SELECT 
	constituency
	,party
	,votes
	,RANK() OVER (PARTITION BY constituency ORDER BY votes DESC) posn
  	FROM ge
	WHERE constituency LIKE 'S%'
    AND yr  = 2017) a
WHERE posn=1
GROUP BY party
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sky丶Mamba

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值