Tôi có một bảng (T1) với các cột sau: bộ phận, ngày tháng, tổng số. Điều tôi muốn đạt được là bán bộ phận mỗi tháng trong một năm kể từ ngày bắt đầu và lùi lại 1 năm. Có thể truy vấn sau sẽ hiển thị tốt hơn những gì tôi muốn đạt được.Thêm hàng giả vào kết quả truy vấn
-- Create the table T1
CREATE TABLE [dbo].[T1](
[department] [nvarchar](50) NULL,
[dateofsale] [datetime] NULL,
[totalsales] [decimal](18, 5) NULL
) ON [PRIMARY]
-- Add some data
INSERT [dbo].[T1] ([department], [dateofsale], [totalsales]) VALUES (N'0001', CAST(0x0000A29B00000000 AS DateTime), CAST(200.00000 AS Decimal(18, 5)))
INSERT [dbo].[T1] ([department], [dateofsale], [totalsales]) VALUES (N'0001', CAST(0x0000A27D00000000 AS DateTime), CAST(300.00000 AS Decimal(18, 5)))
INSERT [dbo].[T1] ([department], [dateofsale], [totalsales]) VALUES (N'0001', CAST(0x0000A29C00000000 AS DateTime), CAST(200.00000 AS Decimal(18, 5)))
-- The query
declare @dataBegin datetime
declare @dataEnd datetime
set @dataEnd = '21/12/2013'
set @dataBegin = DATEADD(month,-11, @dataEnd) - (DAY(@dataEnd)-1)
set @dataEnd = DATEADD(month,1, @dataEnd) - (DAY(@dataEnd))
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)
ORDER BY department,MONTH(dateofsale), YEAR(dateofsale)
Với các dữ liệu thêm vào trước kết quả của truy vấn sẽ được như sau:
department /totsales/ month /year
0001/ 300.00000 /11 /2013
0001/ 400.00000 /12 /2013
Vấn đề là tôi muốn cũng là tháng mà có một giá trị không như Tổng lượng bán. Vì vậy, kết quả phải:
department /totsales/ month /year 0001/ 0 /1 /2013 0001/ 0 /2 /2013 0001/ 0 /3 /2013 0001/ 0 /4 /2013 0001/ 0 /5 /2013 0001/ 0 /6 /2013 0001/ 0 /7 /2013 0001/ 0 /8 /2013 0001/ 0 /9 /2013 0001/ 0 /10 /2013 0001/ 300.00000 /11 /2013 0001/ 400.00000 /12 /2013
Làm thế nào tôi có thể làm điều đó?