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 小时前
Viking AI 搜索 CLI 正式发布:会说话,就能做搜索推荐
数据库·人工智能·开源
TechWJ2 小时前
数据库在公司内网,出差路上想查数据怎么办?
服务器·数据库·mariadb
我是一颗柠檬2 小时前
【MySQL全面教学】MySQL事务与ACID Day9(2026年)
数据库·后端·mysql
橙子圆1232 小时前
Redis知识9之集群
数据库·redis·缓存
BlackHeart12033 小时前
【SQL】Oracle中序列(Sequence)作为默认值引发的ORA-00979
数据库·sql·oracle
bug菌3 小时前
【SpringBoot 3.x 第254节】夯爆了,数据库访问性能优化实战详解!
数据库·spring boot·后端
xxl大卡3 小时前
MySQL的执行流程
数据库·mysql
chicheese4 小时前
MySQL优化实践:选错JOIN 驱动表,性能相差几十倍
数据库·mysql
無限進步D4 小时前
MySQL 单行函数
数据库·mysql
AI人工智能+电脑小能手4 小时前
【大白话说Java面试题 第77题】【Mysql篇】第7题:回表查询与全表扫描的区别?
java·开发语言·数据库·mysql·面试