这是我使用的示例数据。根据这些数据,我需要创建滚动季度报告。换句话说,月度报告回顾了 3 个月。问题是我需要报告平均值和总和。以下是我正在寻找的输出格式。
我试图弄清楚实现这一点的最佳方法是什么?我应该按季度计算还是应该按月计算?
目前这个过程是在 Excel 中完成的,所以我实际上正在处理还没有关系的表。
蛮力解决方案
WITH MonthData AS (
SELECT (YEAR(Date) - 2000) * 12 + MONTH(Date) AS MonthNumber
,Count1
,Count2
FROM Table
)
,QuarterData AS (
SELECT MAX(MonthNumber) AS MonthNumber
,SUM(Count1)/COUNT(1) AS MeanCount1
,SUM(Count2)/COUNT(1) AS MeanCount2
,SUM(Count1) AS SumCount1
,SUM(Count2) AS SumCount2
FROM MonthData
GROUP BY MonthNumber / 3
UNION ALL
SELECT MAX(MonthNumber)
,SUM(Count1)/COUNT(1)
,SUM(Count2)/COUNT(1)
,SUM(Count1)
,SUM(Count2)
FROM MonthData
GROUP BY (MonthNumber + 1) / 3
UNION ALL
SELECT MAX(MonthNumber)
,SUM(Count1)/COUNT(1)
,SUM(Count2)/COUNT(1)
,SUM(Count1)
,SUM(Count2)
FROM MonthData
GROUP BY (MonthNumber + 2) / 3
)
SELECT DATEADD(month, MonthNumber, '20000101') AS Period
,MeanCount1
,MeanCount2
,SumCount1
,SumCount2
FROM QuarterData