SQLZOO附加题练习 - Window functions

前言

SQLZOO里面的题还是比较适合初学者的,这里仅仅作为巩固基础,同时因为这道题目前搜不到相应的答案,所以做个小小的分享~
PS:非小白玩家可以去LeetCode、牛客网、CodeWars上刷题更佳

题目

General Elections were held in the UK in 2015 and 2017. Every citizen votes in a constituency. The candidate who gains the most votes becomes MP for that constituency.
All these results are recorded in a table ge

yrfirstNamelastNameconstituencypartyvotes
2015IanMurrayS14000024Labour19293
2015NeilHayS14000024Scottish National Party16656
2015MilesBriggsS14000024Conservative8626
2015PhylMeyerS14000024Green2090
2015PramodSubbaramanS14000024Liberal Democrat1823
2015PaulMarshallS14000024UK Independence Party601
2015ColinFoxS14000024Scottish Socialist Party197
2017IanMURRAYS14000024Labour26269
2017JimEADIES14000024SNP10755
2017Stephanie Jane HarleySMITHS14000024Conservative9428
2017Alan ChristopherBEALS14000024Liberal Democrats1388

1.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.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.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) 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.

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 
	a.constituency,
	a.party
FROM
(SELECT 
	constituency,
	party,
    RANK() over(partition by constituency order by votes DESC) as posn
FROM 
	ge
WHERE 
	constituency  BETWEEN 'S14000021' AND 'S14000026'
    AND yr  = 2017) a
WHERE a.posn = 1

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

# 这道题想了一会儿
SELECT
	a.party, 
	count(1)
FROM
(SELECT 
	constituency,
	party,
	RANK() over(partition by constituency order by votes DESC) as posn
 FROM 
 	ge
 WHERE 
 	constituency like 'S%'
    AND yr  = 2017) a 
WHERE a.posn =1
GROUP BY a.party
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值