如何在SQL SERVER查询中显示零计数

时间:2015-07-01 04:45:30

标签: sql sql-server sql-server-2012

我想知道我们如何显示ZERO计数?我只有一个表,我正在按月计算,但是一些月没有任何行,SQL Server在计数期间跳过那个月,但我需要在我的报告中显示。

这是我正在使用的查询:

SELECT 
    MONTH(createdDate) [Month], 
    ISNULL(COUNT(id), 0) [Count]
FROM 
    [PocketLife].[dbo].[Notifications]
WHERE 
    description = 'Welcome to Pocket Link' AND 
    YEAR(CAST(createdDate as DATE)) = YEAR(GETDATE())
GROUP BY 
    MONTH(createdDate)

目前上面的查询显示如下,但它缺少第一个月的ZERO记录。

Month   Count
--------------
2            5 
3          295 
4         8295 
5       149855 
6       447752 
7         6311 

但它应显示如下,这是实际的结果:

Month   Count
--------------
1            0 
2            5 
3          295 
4         8295 
5       149855 
6       447752 
7         6311 

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:4)

您可以使用1到12之间的Tally Table作为月份列表,然后对您的查询执行LEFT JOIN。为N添加额外的过滤器,以便它只返回当前月份的记录。

Cte的内容替换为原始查询。

WITH Cte([Month], [Count]) AS(
    SELECT 2, 5 UNION ALL
    SELECT 3, 295 UNION ALL
    SELECT 4, 8295 UNION ALL
    SELECT 5, 149855 UNION ALL
    SELECT 6, 447752 UNION ALL
    SELECT 7, 6311
),
CteTally(N) AS(
    SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL 
    SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
    SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL 
    SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
)
SELECT
    t.N AS [Month],
    ISNULL(c.Count, 0) AS [Count]
FROM CteTally t
LEFT JOIN Cte c
    ON t.N =c.Month
WHERE
    t.N <= MONTH(GETDATE())

答案 1 :(得分:1)

这有点奇怪,但你可以去

SELECT 0 [Month], 0 [Count]
UNION ALL
SELECT MONTH(createdDate) [Month], ISNULL(COUNT(id), 0) [Count]
      FROM [PocketLife].[dbo].[Notifications]
        WHERE description = 'Welcome to Pocket Link' AND 
          YEAR(CAST(createdDate as DATE)) = YEAR(GETDATE())
            GROUP BY MONTH(createdDate)

答案 2 :(得分:1)

这可能会对你有所帮助。

Set Nocount On;

Declare  @LastMonth     Int = 1

Select  @LastMonth = Datepart(Month, Max(n.createdDate))
From    [PocketLife].[dbo].[Notifications] As n With (Nolock)

;With MonthCte As
(
    Select  1 As [Month]

    Union All

    Select  ([Month] + 1)
    From    MonthCte As m
    Where   m.[Month] < @LastMonth
)

Select   mc.[Month]
        ,ISNULL(COUNT(id), 0) [Count]
From    MonthCte As mc With (Nolock)
        Left Join [PocketLife].[dbo].[Notifications] As n On mc.[Month] = Datepart(n.createdDate)
Where   description = 'Welcome to Pocket Link'
        AND YEAR(CAST(createdDate as DATE)) = YEAR(GETDATE()
Group By mc.[Month]

答案 3 :(得分:1)

3