Question

CODE :

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

Result

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

need

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

thank you dear

Was it helpful?

Solution

I don't have SQL Server 2012 on hand to test this, but the following should work:

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

It counts the number in each group. If there are enough, then it displays the average.

By the way, it is generally a bad idea to use a reserved word such as count as the name of a variable. Also, coalesce is standard SQL whereas isnull is not. And, this assumes that you have data for each year.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top