2013-10-30 48 views
0

這是我使用的示例數據。 根據這些數據,我需要創建滾動季度報告。換句話說,每月報告回顧3個月。問題是我需要報告平價和金額。以下是我在尋找的輸出格式。滾動季度的SQL報告

我想弄清楚什麼是實現這個最好的方法? 我應該按季度進行計算,還是應該每月進行一次計算?

目前這個過程是在Excel中完成的,所以我實際上正在處理那些沒有關係的表。

enter image description here

enter image description here

回答

0

蠻力溶液

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