sql实战解析-sum()over(partition by xx order by xx)

该窗口函数功能

sum( c )over( partition by a order by b) 按照一定规则汇总c的值,具体规则为以a分组,每组内按照b进行排序,汇总第一行至当前行的c的加和值。

从简单开始一步一步讲,

1、sum( )over( ) 对所有行进行求和

2、sum( )over( order by ) 按照order by 对应字段的顺序,进行累计求和,即第一行到当前行,默认order by 是升序排序(asc),也可以通过指定降序排序(desc)

生成测试数据

复制代码
with aa as
( 
SELECT 1 a,1 b, 3 c  union all 
SELECT 2 a,2 b, 3 c  union all
SELECT 3 a,3 b, 3 c  union all
SELECT 4 a,4 b, 3 c  union all
SELECT 5 a,5 b, 3 c  union all
SELECT 6 a,5 b, 3 c  union all
SELECT 7 a,2 b, 3 c  union all
SELECT 8 a,2 b, 8 c  union all
SELECT 9 a,3 b, 3 c 
)
SELECT a,b,c,
sum(c) over(order by b) sum1,--有排序,求和当前行所在顺序号的C列所有值
sum(c) over() sum2--无排序,求和 C列所有值
from aa

结果讲解

3、sum( )over( partition by xx order by xx) 在 sum( )over( order by xx) 基础之上,增加一个分组动作,所有的计算都在分组内生效,即在每个分区内,进行sum( )over( order by xx) 的操作。

复制代码
with aa as
( 
SELECT 1 a,1 b, 3 c  union all 
SELECT 2 a,2 b, 3 c  union all
SELECT 3 a,3 b, 3 c  union all
SELECT 4 a,4 b, 3 c  union all
SELECT 5 a,5 b, 3 c  union all
SELECT 6 a,5 b, 3 c  union all
SELECT 7 a,2 b, 3 c  union all
SELECT 8 a,2 b, 8 c  union all
SELECT 9 a,3 b, 3 c 
)
SELECT a,b,c,
sum(c) over(partition by a order by b) sum3 --分组排序,求和当前行所在顺序号的C列所有值
from aa

结果分析

相关推荐
阿坤带你走近大数据1 分钟前
Oracle专家级数据库工程师的认知与经验
数据库·oracle
ZePingPingZe10 分钟前
MySQL-InnoDB锁与事务
数据库·mysql
韩立学长22 分钟前
Springboot森林资源检测管理系统xowdi7nq(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
h79971023 分钟前
高效统计mysql数据踩坑笔记
数据库·mysql
爱可生开源社区25 分钟前
在数据库迁移中,如何让 AI 真正“可用、可信、可落地”?
数据库·sql·llm
猿小喵27 分钟前
TDSQL-MySQL相对MySQL5.7版本主从复制性能优化
数据库·mysql·性能优化
姓蔡小朋友31 分钟前
MySQL读写锁(元数据锁、意向锁、行锁、间隙锁、临键锁)
数据库·mysql
山峰哥33 分钟前
SQL性能优化实战:从索引策略到查询优化案例全解析
大数据·数据库·sql·oracle·性能优化·架构
rannn_11134 分钟前
【SQL题解】力扣高频 SQL 50题|DAY5
数据库·后端·sql·leetcode·题解