分析函数和开窗函数
数据源
with base_source as (
select '李紫萼' as username, '河北' as school, '80' as score from dual union all
select '白迪克' as username, '河北' as school, '85' as score from dual union all
select '王旅' as username, '河北' as school, '85' as score from dual union all
select '李排' as username, '河北' as school, '90' as score from dual union all
select '苏深度' as username, '河北' as school, '100' as score from dual union all
select '李定' as username, '北京' as school, '76' as score from dual union all
select '高都' as username, '北京' as school, '84' as score from dual union all
select '王部' as username, '北京' as school, '90' as score from dual union all
select '李科' as username, '北京' as school, '94' as score from dual union all
select '苏通' as username, '北京' as school, '99' as score from dual )
select * from base_source b
排名函数和分析函数
常见的分析函数:
rownum
:对结果集进行排序row_number()
:对结果集进行分组排序rank()
:对结果集进行分组排序,排序字段值相同 序号相同,跳跃排序desnse_rank()
:对结果集进行分组排序,排序字段值相同 序号相同,顺序排序
以上3个对结果集进行分组排序,都需要over(partition by ... order by ...)
子句的配合;
partition by
和group by
类似,前者不会改变记录的总数,后者会将记录进行合并
rownum
直接使用,针对的是所有结果进行排序,没有排序依据
select rownum, b.* from base_source b
row_number
select row_number() over(partition by b.school order by b.score ) rn , b.* from base_source b
rank
select rank() over(partition by b.school order by b.score ) rn , b.* from base_source b
dense_rank
select dense_rank() over(partition by b.school order by b.score ) rn , b.* from base_source b
开窗函数 over()
可以配合子句partition by
,order by
over(partition by … order by …)
配合sum()
select sum(b.score) over(partition by b.school order by b.score ) rn , b.* from base_source b
配合count()
select count(*) over(partition by b.school order by b.score ) rn , b.* from base_source b