【问题标题】:how can I calculate totals within a query, depending on the date?如何根据日期计算查询中的总数?
【发布时间】:2020-05-28 12:57:23
【问题描述】:

您可以在下面看到我的查询,结果如下:

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”值相加。 如果出勤状态是 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】:

    我了解到您想在第一行之后重置总和,其中 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多