在查询结果上添加假行

Eva*_*d.i 7 t-sql sql-server

我有一个表(T1),其中包含以下列:department,dateofsale,totalsales.我想要实现的是从开始日起一年内每月销售部门,并向后退一年.也许以下查询将更好地展示我想要实现的目标.

-- 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)
Run Code Online (Sandbox Code Playgroud)

在查询结果之前添加数据将如下:

    department  /totsales/  month /year
    0001/ 300.00000 /11 /2013
    0001/ 400.00000 /12 /2013
Run Code Online (Sandbox Code Playgroud)

问题是我还想要总数为零的月份.所以结果必须是:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Tim*_*Tim 1

您可以创建两个查询并对它们进行 UNION,或者使用 CTE 来制造缺失的行。我理解你的意思是你没有11月之前的数据。

WITH months
AS 
( 
    SELECT 2013 as yr, 1 as mnth     
    UNION ALL 
    SELECT 2013 as yr, mnth+1 as mnth
    FROM months
    WHERE  mnth < 12      
) select months.yr, months.mnth, department, isnull(totsales,0.00) as totsales
from months
left join sales on sales.yr = months.yr and sales.month = months.mnth
Run Code Online (Sandbox Code Playgroud)

只需使用 datepart 函数从销售日期中提取月份即可。上面的查询只是向您展示如何获取数据中没有的月份。