SQL Server - 即使没有结果对应表,也要获取计数?

时间:2014-02-23 20:28:50

标签: sql sql-server

以下查询返回过去12个月内为开发人员创建的问题。下面的查询工作正常,但我希望在没有匹配时返回0.

SELECT 
   count(1) as count,
   MONTH(pro.[DATE_CREATED]) AS MONTHNAME, 
   YEAR(pro.[DATE_CREATED]) AS YEARNAME ,
   problemStatus.TypeName
FROM    
   [TestDB].[dbo].PROBLEMS AS pro 
LEFT JOIN 
   [TestDB].[dbo].PROBLEMSTATUS AS problemStatus ON problemStatus.ID = pro.ID_STATUS 
LEFT JOIN 
   [TestDB].[dbo].CUSTOMER AS cust ON pro.ID = cust.ID 
WHERE 
   pro.ID = 1010101010
   AND pro.[DATE_CREATED] >= DATEADD(m, -6, current_timestamp) 
GROUP BY 
   MONTH(pro.[DATE_CREATED]), 
   YEAR(pro.[DATE_CREATED]), 
   problemStatus.type
ORDER BY 
   MONTH(pro.[DATE_CREATED]) DESC

现在查询返回,

Count   Month   Year    Status
1   12  2013    Fixed
1   11  2013    Fixed
1   9   2013    Fixed
1   8   2013    Fixed
1   2   2014    Fixed
1   1   2014    Opened
1   1   2014    Fixed

我希望此返回

Count   Month   Year    Status
1   12  2013    Fixed
0   12  2013    Opened
1   11  2013    Fixed
0   11  2013    Opened
1   9   2013    Fixed
0   9   2013    Opened
1   8   2013    Fixed
0   8   2013    Opened
1   2   2014    Fixed
0   2   2014    Opened
1   1   2014    Opened
1   1   2014    Fixed

1 个答案:

答案 0 :(得分:1)

如果表格中包含所有月份的数据,但不是ID,请尝试以下操作:

SELECT sum(case when pro.ID = 1010101010 then 1 else 0 end) as count,
       MONTH(pro.[DATE_CREATED]) AS MONTHNAME, 
       YEAR(pro.[DATE_CREATED]) AS YEARNAME ,
       coalesce(max(case when pro.ID = 1010101010 then problemStatus.TypeName end), 'Opened') as problemStatus
FROM    [TestDB].[dbo].PROBLEMS AS pro 
left JOIN [TestDB].[dbo].PROBLEMSTATUS AS problemStatus 
ON problemStatus.ID = pro.ID_STATUS 
left  JOIN [TestDB].[dbo].CUSTOMER AS cust 
ON  pro.ID = cust.ID 
WHERE pro.[DATE_CREATED] >= DATEADD(m, -6, current_timestamp) 
GROUP BY MONTH(pro.[DATE_CREATED]), YEAR(pro.[DATE_CREATED]) , problemStatus.type
ORDER BY MONTH(pro.[DATE_CREATED]) DESC;