SQL 每周汇总过去 4 周

SQL Roll Up Last 4 Week by week

我有一个原始数据,如下面的 table 所示。我想得到(总结)前 4 周 data.Can 谁能指导我如何通过 SQL Select 查询得到这个。

原始数据table:

Week    Year    Category    Weekly Total
9       2017      Motor           8
8       2017      Car             7
8       2017      Motor           5
7       2017      Car             4
6       2017      Car             8
5       2017      Car             16
5       2017      Motor           15
4       2017      Car             8
3       2017      Car             5
2       2017      Car             3
1       2017      Car             12
52      2016      Car             8
51     2016       Car             6

预期输出:

Week    Year    4Weeks Total
9       2017        32
8       2017        55
7       2017        51
6       2017        52
5       2017        47
4       2017        28
3       2017        28
2       2017        29
1       2017        26
52      2016        14
51      2016        6

您可以使用 apply:

with t as (
      select week, year, sum(weeklytotal) as weeklytotal
      from t
      group by week, year
     )
select t.week, t.year, t4.total4
from t outer apply
     (select sum(t4.weeklytotal) as total4
      from (select t4.*
            from t t4
            where t4.year < t.year or
                  (t4.year = t.year and t4.week <= t.week)
            order by t4.year desc, t4.week desc
           ) t4
     ) t4;

这假设(如在您的样本数据中)您每周都有数据。

您可以在 CTE 中找到聚合。之后,您可以在相关子查询中找到所需的 4 周总和。

with cte
as (
    select week, year, sum(weekly_total) total
    from your_table
    group by week, year
    )
select week, year, (
        select sum(total)
        from (
            select top 4 total
            from cte t2
            where t2.year * 100 + t2.week <= t1.year * 100 + t1.week
            order by year desc, week desc
            ) x
        )
from cte t1;

生产:

week    year    total
9       2017    32
8       2017    55
7       2017    51
6       2017    52
5       2017    47
4       2017    28
3       2017    28
2       2017    29
1       2017    26
52      2016    14
51      2016    6

Demo