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

结果分析

相关推荐
云和数据.ChenGuang15 分钟前
uri: mongodb://jack:123456@localhost://27017 数据库访问其他的写法
数据库·mongodb·oracle
ManageEngineITSM40 分钟前
IT 服务自动化的时代:让效率与体验共进
运维·数据库·人工智能·自动化·itsm·工单系统
SelectDB42 分钟前
Apache Doris 内部数据裁剪与过滤机制的实现原理
数据库·数据分析·github
Derrick__11 小时前
Python访问数据库——使用SQLite
数据库·python·sqlite
Databend1 小时前
Databend 九月月报:自增列 AUTOINCREMENT 与行级安全
数据库
-雷阵雨-2 小时前
MySQL——数据库入门指南
数据库·mysql
ZhengEnCi2 小时前
SQL 分组排序限制查询技术解析-GROUP-BY-ORDER-BY-DESC-LIMIT 实战应用
后端·sql
玄妙尽在颠倒间2 小时前
SQL中的四大核心语言:DQL、DML、DDL、DCL
大数据·数据库
ZhengEnCi2 小时前
SQL统计查询入门宝典-COUNT-GROUP-BY技术解析
后端·sql
苏打水com3 小时前
企业级数据库实操手册:从架构部署到安全运维的落地指南
数据库·后端