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.