You do not need to model the missing lines, just get the correct values ββfor it.
Note: data must be rotated not only by year-month, but also by department. Otherwise, you will get a NULL value
-- Create the table T1 DECLARE @T1 TABLE( [department] [nvarchar](50) NULL, [dateofsale] [datetime] NULL, [totalsales] [decimal](18, 5) NULL ) -- Add some data INSERT @T1([department], [dateofsale], [totalsales]) VALUES (N'0001', CAST(0x0000A29B00000000 AS DateTime), CAST(200.00000 AS Decimal(18, 5))) INSERT @T1([department], [dateofsale], [totalsales]) VALUES (N'0001', CAST(0x0000A27D00000000 AS DateTime), CAST(300.00000 AS Decimal(18, 5))) INSERT @T1([department], [dateofsale], [totalsales]) VALUES (N'0001', CAST(0x0000A29C00000000 AS DateTime), CAST(200.00000 AS Decimal(18, 5))) INSERT @T1([department], [dateofsale], [totalsales]) VALUES (N'0003', CAST(0x0000A29C00000000 AS DateTime), CAST(100.00000 AS Decimal(18, 5))) -- The query DECLARE @dataBegin DATETIME DECLARE @dataEnd DATETIME SET @dataEnd = '20140101' SET @dataBegin = DATEADD(month, - 11, @dataEnd) - (DAY(@dataEnd) - 1) SET @dataEnd = DATEADD(month, 1, @dataEnd) - (DAY(@dataEnd)); WITH Months ( MonthNr ,Year ,Department ) AS ( SELECT MonthNr ,Y.Year ,D.department FROM ( VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12) ) M(MonthNr) CROSS JOIN ( SELECT DISTINCT T.department FROM @T1 T ) D CROSS JOIN ( SELECT year FROM ( VALUES (2013) --insert as many years as you need ) T(year) ) Y ) SELECT M.department ,ISNULL(T.totsales, 0) totalSales ,M.MonthNr month ,M.year FROM Months M LEFT JOIN ( SELECT department ,SUM(totalsales) AS totsales ,MONTH(dateofsale) AS month ,YEAR(dateofsale) AS year FROM @T1 WHERE dateofsale >= @dataBegin AND dateofsale < @dataEnd GROUP BY department ,MONTH(dateofsale) ,YEAR(dateofsale) ) T ON T.month = M.MonthNr and T.department = M.Department ORDER BY department ,M.MonthNr ,M.Year
Result:
department totalSales month year --------------- --------------------- ----------- ----------- 0001 0.00000 1 2013 0001 0.00000 2 2013 0001 0.00000 3 2013 0001 0.00000 4 2013 0001 0.00000 5 2013 0001 0.00000 6 2013 0001 0.00000 7 2013 0001 0.00000 8 2013 0001 0.00000 9 2013 0001 0.00000 10 2013 0001 300.00000 11 2013 0001 400.00000 12 2013 0003 0.00000 1 2013 0003 0.00000 2 2013 0003 0.00000 3 2013 0003 0.00000 4 2013 0003 0.00000 5 2013 0003 0.00000 6 2013 0003 0.00000 7 2013 0003 0.00000 8 2013 0003 0.00000 9 2013 0003 0.00000 10 2013 0003 0.00000 11 2013 0003 100.00000 12 2013