使用数据透视的各个分组的汇总总和?

时间:2019-03-27 19:35:02

标签: sql oracle

我试图获取过去3天中每个单独组的汇总金额。但是,我没有达到我的期望。谁能教我如何产生预期的输出,也许使用数据透视?

但是,我的结果将各组分开,当组为红色时给出结果,如果为黄色则为null。但是,我希望得到这样的结果:即使该组是黄色的,数据仍然不是空值,而只是重复先前的数字。也许尝试与枢轴?

select *,
case when group = 'Red' then count(NVL(amount,0)) OVER (PARTITION BY ACCOUNT, group ORDER BY day_number range 2 PRECEDING),
case when group = 'Yellow' then count(NVL(amount,0)) OVER (PARTITION BY ACCOUNT, group ORDER BY day_number range 2 PRECEDING)
from table

预期输出

Account Group   Sum day_number  Red Yellow
abc     Red     20  1           20  0
abc     Red     30  3           50  0
abc     Yellow  40  4           50  40
def     Red     20  5           20  40
def     Yellow  50  8           0   50
def     Yellow  20  9           0   70

错误的输出

Account Group   Sum day_number  Red Yellow
abc     Red     20  1           20  
abc     Red     30  3           50  
abc     Yellow  40  4               40
def     Red     20  5           20  
def     Yellow  50  8               50
def     Yellow  20  9               70

2 个答案:

答案 0 :(得分:1)

我认为您最想使用sum()而不是count()

select t.*,
       (case when group = 'Red'
             then sum(amount) over (partition by account, group order by day_number range between 2 preceding and current row)
        end) as red,
       (case when group = 'Yellow'
             then sum(amount) over (partition by account, group order by day_number range between 2 preceding and current row)
        end) as red
from table t

答案 1 :(得分:1)

如果要使redyellow列与帐户和组无关,则只需删除partition by部分。

dbfiddle demo

select t.*,
       nvl(sum(case grp when 'Red'    then amount end) 
           over (order by day_number range 2 preceding), 0) red,
       nvl(sum(case grp when 'Yellow' then amount end) 
           over (order by day_number range 2 preceding), 0) yellow
  from t

给我们结果:

ACCOUNT GRP        AMOUNT DAY_NUMBER        RED     YELLOW
------- ------ ---------- ---------- ---------- ----------
abc     Red            20          1         20          0
abc     Red            30          3         50          0
abc     Yellow         40          4         30         40
def     Red            20          5         50         40
def     Yellow         50          8          0         50
def     Yellow         20          9          0         70

请注意,列RED的第三行(您键入50,查询显示30)有所不同,但是对于日期4,前两天只有一个红色值,即{ {1}}。

如果您只需要重复null值,则改为使用30,但这对我来说没有意义。

您可以使用lag进行此操作,但是必须在子查询中正确准备数据,然后进行数据透视。在这种情况下,pivot语法更易读。