CREATE TABLE #ItemSales ( ItemID int , DateBought datetime , Quantity int , CONSTRAINT PK_ItemSales_ID_Bought PRIMARY KEY CLUSTERED( ItemID , DateBought ) ); INSERT INTO #ItemSales SELECT 1 , '2000-10-20' , 62 UNION ALL SELECT 1 , '2000-09-01' , 13 UNION ALL SELECT 1 , '2000-11-01' , 45 UNION ALL SELECT 1 , '2000-06-01' , 89 UNION ALL SELECT 2 , '2000-06-01' , 37 UNION ALL SELECT 2 , '2000-10-24' , 81 UNION ALL SELECT 2 , '2000-10-12' , 56;
SELECT * FROM #ItemSales ORDER BY ItemID , DateBought DESC;
GO
SELECT i1.ItemID , i1.DateBought , ( SELECT AVG( i2.Quantity ) FROM #ItemSales AS i2 WHERE i2.ItemID = i1.ItemID And DATEDIFF( mm , i2.DateBought , i1.DateBought ) Between 0 And 3 ) AS MovingAverageOver3Months FROM #ItemSales AS i1 ORDER BY i1.ItemID , i1.DateBought DESC;
DROP TABLE #ItemSales; GO |