Oracle 分析函数和开窗函数

分析函数和开窗函数

数据源

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 bygroup by类似,前者不会改变记录的总数,后者会将记录进行合并

rownum

直接使用,针对的是所有结果进行排序,没有排序依据

select rownum, b.* from base_source b

rownum

row_number

select row_number() over(partition by b.school order by b.score ) rn , b.* from base_source b

row_number

rank

select rank() over(partition by b.school order by b.score ) rn , b.* from base_source b

rank

dense_rank

select dense_rank() over(partition by b.school order by b.score ) rn , b.* from base_source b

dense_rank

开窗函数 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

参考:
oracle------分析函数和开窗函数over( )

发布了241 篇原创文章 · 获赞 14 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_29150765/article/details/101023777