sql 之窗口函数

一、基本语法

函数名(列) over(选项)

选项:partition by 列,order by 列

  • over(partition by xxx),按列xxx分组。可以按多个列进行分组,over(partition by xxx,yyy),按xxx,yyy列进行分组
  • over(partition by xxx order by aaa),按列xxx分组,按列aaa排序
  • over(order by aaa),按列aaa排序
  • over括号里的选项根据实际情况使用

二、聚合窗口函数

聚合函数与窗口函数结合使用。

聚合窗口函数、聚合函数的区别

使用聚合函数查询,会改变原有表结构
select student_id,count(sid) from score where num >= 60 group by student_id;

使用窗口函数查询,不改变原有表结构
seledt student_id,count(sid) over(partition by student_id) from score where num >= 60;

常用来借据的问题

三、排序窗口函数

  • row_number()
    赋予唯一的连续位次。
    例如,有3条排在第1位时,排序为:1,2,3,4······

  • rank()
    在计算排序时,若存在相同位次,会跳过之后的位次。
    例如,有3条数据排在第1位时,排序为:1,1,1,4······

  • dense_rank()
    在计算排序时,若存在相同位次,不会跳过之后的位次。
    例如,有3条排在第1位时,排序为:1,1,1,2······

  • ntile()

四、位置移动窗口函数

  • lead(col,n)

  • lag(col,n)

五、其他窗口函数

  • first_value(column)

  • last_value(column)

rows between unbounded preceding and current row


参考:
https://blog.csdn.net/feizuiku0116/article/details/121148110
https://blog.csdn.net/haifeng112612/article/details/114977365
https://zhuanlan.zhihu.com/p/475913134

posted @   捷后愚生  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示