下面您将看到我的查询,它给出以下结果:
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_key累加“ money_step”的值。如果Attenance_status是ID的第二次“ 15”,则计数器应从头算起。对于ID_KEY = 1,它应如下所示:
累积:
Row 1:20
Row 2: 80
Row 3: 100
Row 4: 120
如何在查询中执行此操作?有人可以帮我吗?
我了解您想在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