带有滚动窗口的SQL聚合

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

希望有人可以启发我。我有一个基于每周的数据列-该周的最后一天,还有类型和持续时间。我想在每个ID的每周的单独列中汇总每种类型的持续时间(将其持续到第1周,第2周等)。

所以,这是输入:

enter image description here

这是我想要得到的:

enter image description here

在这种情况下,类型的数量很小,因此我们可以手动将新列定义为SUM(CASE WHEN type='A' THEN duration ELSE 0 END) "A"

总体上看似可行,但我无法将它们全部组装在一起。。

sql sql-server aggregate rdbms
1个回答
1
投票

考虑:

select
    id,
    dense_rank() over(order by week_end_date) week_num
    sum(case when type = 'A' then duration end) a,
    sum(case when type = 'B' then duration end) b,
    sum(case when type = 'C' then duration end) c
from mytable
group by id, week_end_date

查询根据表中可用的日期动态生成星期数(第一个日期为星期1,依此类推)。然后,我们通过id和week进行聚合,并进行条件求和以计算总数。

© www.soinside.com 2019 - 2024. All rights reserved.