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

结果分析

相关推荐
forestsea6 分钟前
MySQL 入门大全:数据类型
数据库·mysql
为自己_带盐34 分钟前
浅聊一下数据库的索引优化
开发语言·数据库·php
gb42152871 小时前
mysql数据库中某个数据表的碎片率自己降低了,mysql数据表对碎片率有自动优化机制吗?
数据库·mysql
AI大模型顾潇1 小时前
[特殊字符] 本地大模型编程实战(29):用大语言模型LLM查询图数据库NEO4J(2)
前端·数据库·人工智能·语言模型·自然语言处理·prompt·neo4j
有时间要学习1 小时前
MySQL——数据类型&&表的约束
数据库·mysql
AI改变未来2 小时前
数据库常见故障排查
数据库
bing_1582 小时前
MongoDB 的核心概念(文档、集合、数据库、BSON)是什么?
数据库·mongodb·oracle
feilieren2 小时前
Windows 安装 Milvus
数据库·ai·milvus
kngines2 小时前
【PostgreSQL数据分析实战:从数据清洗到可视化全流程】附录-D. 扩展插件列表(PostGIS/PostgREST等)
数据库·postgresql·数据分析·pgvector·扩展插件·postgrest·向量数据
星星点点洲2 小时前
【Redis】谈谈Redis的设计
数据库·redis·缓存