按特殊功能分组

时间:2016-05-05 11:08:58

标签: oracle

我有一张桌子

=SUMPRODUCT(--(Registration!AH3:AH1000>=D1+0),--(Registration!AH3:AH1000<=D2+0),--(Registration!AS3:AS1000='Sarah Data'!C62))

.......

从这张表中我想创建一个表

dated          abc     def     gh     jkl    
01.05.2016     2       12      23     16  
02.05.2016     11      7       5      8  
03.05.2016     6       4       9      1  

......
所以,实际上我想要添加所有值,但仅适用于小于所选日期的日期... 我如何实现这一目标。

1 个答案:

答案 0 :(得分:5)

看起来像是总计,你可以使用windowed SUM

SELECT dated
       ,SUM(abc) OVER(ORDER BY dated) AS abc
       ,SUM(def) OVER(ORDER BY dated) AS def
       ,SUM(gh)  OVER(ORDER BY dated) AS gh
       ,SUM(jkl) OVER(ORDER BY dated) AS jkl
FROM t
ORDER BY dated;

LiveDemo

输出:

╔═════════════════════╦═════╦═════╦════╦═════╗
║        dated        ║ abc ║ def ║ gh ║ jkl ║
╠═════════════════════╬═════╬═════╬════╬═════╣
║ 05.01.2016 00:00:00 ║   2 ║  12 ║ 23 ║  16 ║
║ 05.02.2016 00:00:00 ║  13 ║  19 ║ 28 ║  24 ║
║ 05.03.2016 00:00:00 ║  19 ║  23 ║ 37 ║  25 ║
╚═════════════════════╩═════╩═════╩════╩═════╝

修改

  

,如何得到计数,就像第一行一样,count是1,而对于第二行,它是2作为另一列,依此类推....

您可以使用COUNTROW_NUMBER()

SELECT ...
  ,COUNT(*) OVER(ORDER BY dated) AS cnt

LiveDemo2

  

我也可以使用一些计算...比如sum(abc)over(按日期排序)/ count( 100/3作为NMU

是的,您可以进行全方位的计算。但请注意,某些操作必须用派生表(CTE /子查询)包装:

sum(abc) over (order by dated)/COUNT(*) OVER(ORDER BY dated)*100.0/3 as NMU

修改

  

工作正常,除了一件事,这笔款项只适用于月份或季度,意味着增加只会持续到月末,所以当月/季更改时,价值将开始从头开始

然后你需要按(年,月)或(年,季)划分:

SELECT dated
       ,SUM(abc) OVER(PARTITION BY EXTRACT(year from dated),
                                   EXTRACT(month from dated) ORDER BY dated) AS abc

或:

SELECT dated,
      ,SUM(abc) OVER(PARTITION BY to_char(dated, 'YYYY Q') ORDER BY dated) AS abc