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

结果分析

相关推荐
大模型玩家七七2 分钟前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
曾经的三心草4 分钟前
redis-9-哨兵
数据库·redis·bootstrap
明哥说编程8 分钟前
Dataverse自定义表查询优化:D365集成大数据量提速实战【索引配置】
数据库·查询优化·dataverse·dataverse自定义表·索引配置·d365集成·大数据量提速
xiaowu08018 分钟前
C# 拆解 “显式接口实现 + 子类强类型扩展” 的设计思想
数据库·oracle
讯方洋哥33 分钟前
HarmonyOS App开发——关系型数据库应用App开发
数据库·harmonyos
惊讶的猫1 小时前
Redis持久化介绍
数据库·redis·缓存
Apple_羊先森1 小时前
ORACLE数据库巡检SQL脚本--19、磁盘读次数最高的前5条SQL语句
数据库·sql·oracle
全栈前端老曹2 小时前
【MongoDB】Node.js 集成 —— Mongoose ORM、Schema 设计、Model 操作
前端·javascript·数据库·mongodb·node.js·nosql·全栈
神梦流2 小时前
ops-math 算子库的扩展能力:高精度与复数运算的硬件映射策略
服务器·数据库
让学习成为一种生活方式2 小时前
trf v4.09.1 安装与使用--生信工具42-version2
数据库