主知识点九:窗口函数
【知识点引入】
-
- 最后我们要来学习窗口函数
- 【标准语法】
- 窗口函数 over (partition by 用于分组的字段名 order by 用于排序的字段名)
- 常用窗口函数
-
- 【例题讲解】
- 我们以排序窗口函数rank()over()为例
- 窗口函数rank()over()是在指定分区(partition by)对指定字段排序(order by)然后依次赋予排名的函数
- 【指定分区partition by和排序order by】
- 点击链接Window functions - SQLZOO 第三题
- 【题目】
- 查询每一年S14000021选区中所有候选人所在的团体party和选票数votes
- 并且对每一年中的所有候选人根据选票数的高低进行排名posn,选票数最高则为第一名,后续以此类推
- 最后根据团体party和年份yr排序
- 先查看题目表格
- 记录了每一年yr,候选人名字firstname和姓氏lastname,所属选区constituency和团体party,以及选票数votes
- 记录了每一年yr,候选人名字firstname和姓氏lastname,所属选区constituency和团体party,以及选票数votes
- 查询每一年S14000021选区中所有候选人所在的团体party和选票数votes,写出代码
- select
- yr
- ,party
- , votes
- from ge
- where constituency = 'S14000021'
- order by party,yr
- 还需要对筛选出的S14000021选区中的每一年的数据分区然后根据票数高到低排序,用desc降序
- 使用窗口函数
- rank()over(partition by yr order by votes desc) as posn
- 将窗口函数写在select子句后
- 【运行代码】
- select
- yr
- ,party
- , votes
- ,rank()over(partition by yr order by votes desc) as posn
- from ge
- where constituency = 'S14000021'
- order by party,yr
- 【运行结果】
-
- 【运行代码】
- 【excel演示】
- 通过以下代码得到表格
- select
- yr
- ,party
- , votes
- from ge
- where constituency = 'S14000021'
- 通过以下代码得到表格
- 【题目】
- 点击链接Window functions - SQLZOO 第三题