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

问题描述 投票:1回答:1

下面您将看到我的查询,它给出以下结果:

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

Results of the query

我希望“累计”列为每个id_key累加“ money_step”的值。如果Attenance_status是ID的第二次“ 15”,则计数器应从头算起。对于ID_KEY = 1,它应如下所示:

累积:

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

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

sql sql-server tsql window-functions gaps-and-islands
1个回答
0
投票

我了解您想在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
© www.soinside.com 2019 - 2024. All rights reserved.