1.Show the lastName, party and votes for the constituency 'S14000024'in2017.
SELECT lastName, party, votes FROM ge WHERE constituency = 'S14000024'AND yr = 2017 ORDERBY votes DESC
1 2 3 4 5 6 7
2.Show the party and RANK for constituency S14000024 in2017. List the output by party
SELECT party, votes, RANK() OVER (ORDERBY votes DESC) as posn FROM ge WHERE constituency = 'S14000024'AND yr = 2017 ORDERBY party
1 2 3 4 5 6 7
3.Use PARTITIONtoshow the ranking ofeach party in S14000021 ineach year. Include yr, party, votes and ranking (the party with the most votes is1).
SELECT yr,party, votes, RANK() OVER (PARTITIONBY yr ORDERBY votes DESC) as posn FROM ge WHERE constituency = 'S14000021' ORDERBY party,yr
1 2 3 4 5 6
4.Use PARTITIONBY constituency toshow the ranking ofeach party in Edinburgh in2017.Order your results so the winners are shown first, then ordered by constituency.
select constituency,party,votes, rank() over(partitionby constituency orderby votes desc) as posn from ge where yr = 2017and constituency between'S14000021'and'S14000026' orderby posn,constituency
1 2 3 4 5 6 7 8 9 10 11 12
5.Show the parties that won for each Edinburgh constituency in 2017.
selectwithinselect:
select constituency,party from (select constituency,party,votes, rank() over(partitionby constituency orderby votes desc) as posn from ge where yr = 2017and constituency between'S14000021'and'S14000026' orderby posn,constituency)as ge1 where ge1.posn = 1
6.Show how many seats foreach party in Scotland in2017.
select ge1.party,count(*) from (select party, rank() over(partitionby constituency orderby votes desc) as posn from ge where constituency like'S%'and yr = 2017 )as ge1 where ge1.posn = 1 groupby ge1.party
select party2.party,party2.seats from ( select ge1.party,count(*) from (select party, rank() over(partitionby constituency orderby votes desc) as posn from ge where constituency like'S%'and yr = 2017 )as ge1 where ge1.posn = 1 groupby ge1.party )as party2 right join ( selectdistinct party from ge where constituency like'S%'and yr = 2017 )as party1 on (party1.party=party2.party) where party2.party isnotnull
需要最后排除掉party是null的情况
Summary
窗口函数不错子,之后还要深入学习,之后再专门做个窗口函数的笔记吧…
Author:Nananan
Post Date:2021-02-16 09:58:38Update Date:2021-10-22 19:37:40