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

结果分析

相关推荐
夕除27 分钟前
Mysql
数据库·mysql
LaughingZhu38 分钟前
Product Hunt 每日热榜 | 2026-03-28
数据库·人工智能·经验分享·神经网络·chatgpt
知识分享小能手1 小时前
MongoDB入门学习教程,从入门到精通,MongoDB聚合框架(7)
数据库·学习·mongodb
城数派1 小时前
2015-2024年我国1km分辨率逐日地表温度(LST)栅格数据
数据库·arcgis·信息可视化·数据分析·excel
城数派1 小时前
中国全国土壤有机碳密度数据集(2010-2024年)
数据库·arcgis·信息可视化·数据分析·excel
鹓于1 小时前
CRX格式详解:安装、开发与反编译
数据库
IvorySQL2 小时前
PostgreSQL 技术日报 (3月28日)|零停机补丁、约束新特性、性能避坑全收录
数据库·postgresql·开源
smchaopiao2 小时前
数据库优化技巧详解:从LIMIT到索引的提升策略
数据库·oracle
清水白石0082 小时前
Python 编程全景解析:四大核心容器的性能较量、语义之美与高阶实战
开发语言·数据库·python
菜菜小狗的学习笔记2 小时前
黑马程序员Redis--实战篇(黑马点评)
数据库·redis·缓存