我想从包含 Q3 和 Q4 数据的数据集中获取 QoQ,该数据集也有一个报告日期列,每一行都应该有每个财政月的 QoQ 值(由报告日期表示),Q4 应该与 Q3 进行比较,但我的声明似乎只在同一季度内进行比较,即 Q4 与 Q4 进行比较,而不是 Q4 与 Q3 进行比较。
我正在使用该lag
功能,但不确定我做错了什么,如果有人可以请参阅下面的代码。
SELECT [Year],
[SalesDate] as Report_Date,
[Quarter],
Sales,
LAG(Sales, 1, 0) OVER(
PARTITION BY [Year] ,[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) AS [QuarterSales_Offset],
sales - LAG(Sales) OVER(
PARTITION BY [Year] ,[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) as diff,
Case When
LAG(Sales,1,0) OVER(
PARTITION BY [Year],[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) = 0 then null else
(
sales - LAG(Sales,1,0) OVER(
PARTITION BY [Year],[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC))/ LAG(Sales,1,0) OVER(
PARTITION BY [Year],[Quarter]
ORDER BY [Year],
[Quarter],
salesDate
ASC) end as QoQ
FROM dbo.ProductSales_2;
查询输出: