如何在一列中生成多个和?

iibxawm4  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(300)

下面是我的查询,结果如下:

select t.actual_date, 
   t.id_key, 
   t.attendance_status, 
   t.money_step, 
   sum(t.money_step) over (partition by t.id_key order by t.actual_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)as accumulated
from example t
order by t.id_key, t.actual_date


查询结果
我希望“累计”列为每个id\u键加上“money\u step”的值。如果id\u键是id的第二次“15”,则计数器应从开始处累加。对于id_key=1,它应该如下所示:
累积的:

Row 1:20
Row 2: 80
Row 3: 100
Row 4: 120

对于id\u key=2,它应该如下所示:

Row 1: accumulated = 30; attendance_status = 7
Row 2: accumulated = 130; attendance_status = 15
Row 3: accumulated = 30; attendance_status = 15
Row 4: accumulated = 60; attendance_status = 15

15级总是有最晚的日期。从第15级的第二个日期起,每个id的总和应重新开始。所有值​​少于15应视为正常。
如何在查询中执行此操作?有人能帮我吗?

c8ib6hqw

c8ib6hqw1#

试试下面的逻辑-
此处演示

SELECT *,
SUM(A.money_step) over (
    partition by A.id_key, A.P 
    ORDER BY A.actual_date 
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)as accumulated
FROM
(
    SELECT A.*,
    (
        SELECT CASE WHEN COUNT(*) >= 2 THEN 2 ELSE 1 END
        FROM your_table B 
        WHERE B.id_key = A.id_key
        AND B.actual_date <= A.actual_date
        AND attendance_status = 15
    ) P
    FROM your_table A
)A
ORDER BY A.id_key,A.actual_date
bt1cpqcv

bt1cpqcv2#

这是未经测试,因为我没有转录一个图像,然而,我认为这将工作。如果没有,则消耗品样品数据必须在此处显示:

WITH CTE AS
    (SELECT t.actual_date,
            t.id_key,
            t.attendance_status,
            t.money_step,
            ROW_NUMBER() OVER (PARTITION BY t.id_key,
                                            CASE attendance_status WHEN 15 THEN 1 ELSE 0 END
                               ORDER BY t.actual_date) AS RN
     FROM example t)
SELECT C.actual_date,
       C.id_key,
       C.attendance_status,
       C.money_step,
       SUM(t.money_step) OVER (PARTITION BY t.id_key, CASE WHEN RN > 1 THEN 1 ELSE 0 END
                               ORDER BY t.actual_date
                               ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS accumulated
FROM CTE C;
2sbarzqh

2sbarzqh3#

我强烈建议你只使用窗口函数。其实很简单:

SELECT t.*,
       SUM(t.money_step) OVER (PARTITION BY id_key, grp ORDER BY actual_date) as accumulated
FROM (SELECT t.*,
             SUM(CASE WHEN seqnum = 2 AND attendance_status = 15 THEN 1 ELSE 0 END) OVER
                 (PARTITION BY id_key ORDER BY actual_date) as grp
      FROM (SELECT t.*,
                   ROW_NUMBER() OVER (PARTITION BY id_key, attendance_status ORDER BY actual_date) as seqnum
            FROM t
           ) t
     ) t
ORDER BY t.id_key, t.actual_date;

这是一把小提琴。

相关问题