DB2——sum over partition by 的用法

Posted Im X

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DB2——sum over partition by 的用法相关的知识,希望对你有一定的参考价值。

参考的博文出处:http://www.cnblogs.com/luhe/p/4155612.html,对博文进行了修改新增,修改了错误的地方

之前用过row_number(),rank()等排序与over( partition by ... ORDER BY ...),这两个比较好理解: 先分组,然后在组内排名。

今天突然碰到sum(...) over( partition by ... ORDER BY ... ),居然搞不清除怎么执行的,所以查了些资料,做了下实操。

1. 从最简单的开始

  sum(...) over( ),对所有行求和

  sum(...) over( order by ... ),和 =  第一行 到 与当前行同序号行的最后一行的所有值求和,文字不太好理解,请看下图的算法解析。

复制代码
with aa as
( 
SELECT 1 a,1 b, 3 c FROM dual union
SELECT 2 a,2 b, 3 c FROM dual union
SELECT 3 a,3 b, 3 c FROM dual union
SELECT 4 a,4 b, 3 c FROM dual union
SELECT 5 a,5 b, 3 c FROM dual union
SELECT 6 a,5 b, 3 c FROM dual union
SELECT 7 a,2 b, 3 c FROM dual union
SELECT 8 a,2 b, 8 c FROM dual union
SELECT 9 a,3 b, 3 c FROM dual
)
SELECT a,b,c,
sum(c) over(order by b) sum1,--有排序,求和当前行所在顺序号的C列所有值
sum(c) over() sum2--无排序,求和 C列所有值
from aa
复制代码

 

补充 by 松门一枝花:

 

  1. WITH aa AS
  2. ( SELECT 1 a,1 b, 3 c FROM dual
  3. UNION
  4. SELECT 2 a,2 b, 3 c FROM dual
  5. UNION
  6. SELECT 3 a,3 b, 3 c FROM dual
  7. UNION
  8. SELECT 4 a,4 b, 3 c FROM dual
  9. UNION
  10. SELECT 5 a,5 b, 3 c FROM dual
  11. UNION
  12. SELECT 6 a,5 b, 3 c FROM dual
  13. UNION
  14. SELECT 7 a,2 b, 3 c FROM dual
  15. UNION
  16. SELECT 8 a,2 b, 8 c FROM dual
  17. UNION
  18. SELECT 9 a,3 b, 3 c FROM dual
  19. )
  20. SELECT a,
  21. b,
  22. c,
  23. SUM(c) over(order by a) sum1,--有排序,求和当前行所在顺序号的C列所有值--【博主新增的】
  24. SUM(c) over(order by b) sum2,--有排序,求和当前行所在顺序号的C列所有值
  25. SUM(c) over() sum3 FROM aa order by a; --无排序,求和 C列所有值
  26.  


 

2. 与 partition by 结合

  sum(...) over( partition by... ),同组内所行求和

  sum(...) over( partition by... order by ... ),同第1点中的排序求和原理,只是范围限制在组内

复制代码
with aa as
( 
SELECT 1 a,1 b, 3 c FROM dual union
SELECT 2 a,2 b, 3 c FROM dual union
SELECT 3 a,3 b, 3 c FROM dual union
SELECT 4 a,4 b, 3 c FROM dual union
SELECT 5 a,5 b, 3 c FROM dual union
SELECT 6 a,5 b, 3 c FROM dual union
SELECT 7 a,2 b, 3 c FROM dual union
SELECT 7 a,2 b, 8 c FROM dual union
SELECT 9 a,3 b, 3 c FROM dual
)
SELECT a,b,c,sum(c) over( partition by b ) partition_sum,
sum(c) over( partition by b order by a desc) partition_order_sum
  FROM aa;
复制代码

  


 

以上是关于DB2——sum over partition by 的用法的主要内容,如果未能解决你的问题,请参考以下文章

Dplyr 相当于 SUM over PARTITION BY

BigQuery 缺少 SUM OVER PARTITION BY 的行

SUM() OVER (PARTITION BY) AS - 存在重复项时

Hive sum over partition preceding following 累计求和

MariaDB 查询 SUM() OVER (PARTITION BY)

Hive sum over partition preceding following 累计求和