如何根据日期计算查询中的总计?

raogr8fs  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(434)

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

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”的值。如果身份证的出勤状态是第二次“15”,则计数器应从开始处累加。对于id_key=1,它应该如下所示:
累积的:

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

如何在查询中执行此操作?有人能帮我吗?

b09cbbtk

b09cbbtk1#

我知道你想在第一行之后重置总和,其中 attendance_status 有价值 15 . 一个选项使用条件 max() 要定义子组:

select 
    actual_date, 
   id_key, 
   attendance_status, 
   money_step, 
   sum(t.money_step) over (
       partition by id_key, grp 
       order by actual_date
   ) as accumulated
from (
    select 
        e.*,
        max(case when attendance_status = 15 then 1 else 0 end) over(
            partition by id_key 
            order by actual_date 
            rows between unbounded preceding and 1 preceding
        ) grp
    from example e
) e
order by id_key, actual_date

相关问题