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)

生成测试数据

sql 复制代码
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) 的操作。

sql 复制代码
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

结果分析

相关推荐
范小多18 小时前
mysql实战 C# 访问mysql(连载三)
数据库·mysql·oracle·c#
Austindatabases18 小时前
SQLite 开发中的数据库开发规范 --如何提升业务系统性能避免基础BUG
数据库·oracle·sqlite·bug·数据库开发
枫叶丹418 小时前
【Qt开发】Qt窗口(六) -> QMessageBox 消息对话框
c语言·开发语言·数据库·c++·qt·microsoft
星环处相逢18 小时前
MySQL 备份与还原:理论与实战全解析
数据库·mysql
一起养小猫18 小时前
MySQL数据库基础:从三层结构到常用操作
数据库·mysql
l***914718 小时前
【MySQL】深度学习数据库开发技术:使用CC++语言访问数据库
数据库·mysql·数据库开发
Hello.Reader18 小时前
Flink SQL 中的 SELECT & WHERE,批流统一的查询入口
sql·flink·linq
Wang's Blog18 小时前
MongoDB小课堂:精通数据迁移工具 mongoexport 与 mongoimport 的终极指南
数据库·mongodb
一 乐18 小时前
旅游出行|基于Springboot+Vue的旅游出行管理系统设计与实现(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·旅游
“αβ”1 天前
MySQL表的操作
linux·网络·数据库·c++·网络协议·mysql·https