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 小时前
Redis 缓存穿透、缓存击穿、缓存雪崩
数据库·redis
Elastic 中国社区官方博客1 小时前
jina-ocr-v1:在低成本 GPU 上实现更快速的文档解析
大数据·数据库·elasticsearch·搜索引擎·全文检索·jina
于平安1 小时前
MySQL-变量,流程控制与游标
数据库·mysql
我滴老baby1 小时前
检索的上限,在切块时就定了:一次〈民法典〉实测,看懂 ChatDOC 的“上下文检索”
数据库·全文检索·文档处理
Databend1 小时前
Jev 爆火之后,我们把它集成进了数据湖仓
大数据·数据库·agent
数字新视界1 小时前
数据中心基础设施管理系统的智能监测与运维整合剖析
数据库·物联网·数据中心·数据中心基础设施管理·dcim管理系统
于樱花森上飞舞2 小时前
【Redis】哨兵详解
java·开发语言·数据库·redis
李白客2 小时前
向量数据库怎么选:RAG 项目最该比较的 8 个维度(深度拆解)
数据库·aigc
cspttty3 小时前
需求预测校招入门:SQL、Excel、统计模型和业务指标怎么学
大数据·数据库