0

代码 :

SELECT YEAR_ID, Count, ThreeYEARAverage, 
       AVG(Count) OVER (ORDER BY YEAR_ID ROWS 4 PRECEDING) AS FiveYEARAverage 
FROM (SELECT YEAR_ID, ISNULL(Count, 0) AS Count, 
             AVG(ISNULL(Count, 0)) OVER (ORDER BY YEAR_ID ROWS 2 PRECEDING) AS ThreeYEARAverage 
      FROM (SELECT DATEPART(YEAR, Date_plan) AS YEAR_ID, 
            SUM(ISNULL(Amount_produced, 0)) AS Count 
            FROM History_mango   
            WHERE DATEPART(YEAR, Date_plan) BETWEEN '2012' AND '2016' 
                  AND DATEPART(month, Date_plan) =  '09' 
            GROUP BY DATEPART(YEAR, Date_plan)) AS id
      ) AS id1

结果

YEAR_ID Count ThreeYEARAverage  FiveYEARAverage 
2012    22    22.000000         22.000000
2013    555   288.500000        288.500000
2014    100   225.666666        225.666666
2015    88    247.666666        191.250000
2016    200   129.333333        193.000000

需要

YEAR_ID Count ThreeYEARAverage  FiveYEARAverage 
2012    22  
2013    555 
2014    100   225.666666    
2015    88    247.666666
2016    200   129.333333        193.000000

谢谢你亲爱的

4

1 回答 1

0

我手头没有 SQL Server 2012 来测试这个,但以下应该可以工作:

SELECT YEAR_ID, Count,
       (case when count(*) over (rows 2 preceding) >= 3
             then AVG(ISNULL(Count, 0)) OVER (ORDER BY YEAR_ID ROWS 2 PRECEDING) 
        end) AS ThreeYEARAverage,
       (case when count(*) over (rows 4 preceding)
             then AVG(Count) OVER (ORDER BY YEAR_ID ROWS 4 PRECEDING
        end) AS FiveYEARAverage
FROM (SELECT DATEPART(YEAR, Date_plan) AS YEAR_ID,
             SUM(coalesce(Amount_produced, 0)) AS Count
      FROM History_mango
      WHERE DATEPART(YEAR, Date_plan) BETWEEN '2012' AND '2016' AND DATEPART(month, Date_plan) = '09'
      GROUP BY DATEPART(YEAR, Date_plan)
     ) id

它计算每组中的数量。如果有足够的,则显示平均值。

顺便说一句,使用保留字(例如count变量名)通常是个坏主意。此外,coalesce是标准 SQL 而isnull不是。而且,这假设您有每年的数据。

于 2013-03-19T15:53:03.343 回答