在 SQL 报表中计算每周的增长率

Calculate a growth ratio week over week in SQL Statement

我有一个 SQL 服务器 table 包含 [日期]、[类别]、[年]、[周]、[月]、[接收数量]。

这是我为获取过去 4 年每个类别的每周总和 [数量] 而编写的查询。

    SELECT Year([Date]) AS [D_Year]
       , [Week] AS [Week of Year]
       , SUM([Volume Received])AS [Received]
       , [Category]
  FROM [t1]
  WHERE YEAR(Date) in ('2016', '2017', '2018','2019')

  GROUP BY Year([Date]), [Week], [Category]

它给我这个 table:

 > year   week      received     category  
 > 2016     1         51123         A 
 > 2016     2         41123         A 
 > 2016     3         21123         B 
 > 2016     1         5113          D 
 >  ...
 > 2017     18         1113         A
 >  ...
 > 2019     1         11134         C

我正在寻找一份 SQL 报表,它可以提供每个类别每周的平均增长率。

我在 EXCEL 中手动完成了它,但是当我刷新与 SQL 服务器的连接时,它没有更新。

我想要的最终输出是这样的:

> week      ratio      category  
> 1         -0.05         A 
> 1          0.15         B 
> 1          0.02         C 
> 1         -0.25         D
> 2          0.25         A 
> 2         -0.15         B 
> 2          0.02         C 
> 2         -0.25         D

您可以包装现有查询并使用 window 函数 LAG() 获取 [Received]:

的先前值
SELECT
    [D_Year],
    [Week of Year],
    (
        [Received] 
        - LAG([Received]) OVER(PARTITION BY [Category] ORDER BY [D_Year], [Week of Year])
    ) / [Received] [Ratio]
FROM (
    SELECT 
        Year([Date]) AS [D_Year],
        [Week] AS [Week of Year]
        SUM([Volume Received]) AS [Received],
        [Category]
    FROM [t1]
    WHERE YEAR(Date) IN (2016, 2017, 2018, 2019)
    GROUP BY 
        Year([Date]), 
        [Week], 
        [Category]
) t