获取每个月的数据,即使它在sql server中为null

时间:2013-08-19 14:48:02

标签: sql-server

在我的上下文中,客户正在发出请求,并且该请求已保存在数据库中。对于每个月,我想计算每个月的请求数量,所以我尝试过:

Select COUNT(EveLngId) as NbreIncidentPrisEnDirect
FROM T_Evenement as TE inner join T_Historique on HisLngEveId  = EveLngId, T_Param as TPA
WHERE EveLngDosId = 1062
    And EveLngBibId = 268
    And HisLngBibId = 267
    And ParStrIndex = 'RES'
    And TE.EveLngResponsableId = TPA.ParLngId
    And EveDatRedaction = EveDatRealisation
    And year(EveDatRedaction) = '2013'
    group by MONTH(EveDatRedaction)

我得到了那个结果:

enter image description here

如您所见,那一年(2013年)我没有每个月的价值,为什么?因为对于其中一些,值为0.有一种方法可以显示每个月的值,即使该值为0?

2 个答案:

答案 0 :(得分:2)

最佳解决方案是创建日历表并JOIN您的数据。否则,您需要创建一个表:

SELECT 1 AS month, 2013 AS year
UNION ALL
SELECT 2, 2013
UNION ALL
SELECT 3, 2013
UNION ALL
SELECT 4, 2013
...

JOIN与您的查询。

答案 1 :(得分:0)

假设您每个月都有一些数据(虽然不匹配where子句),您可以使用条件聚合:

Select sum(case when EveLngDosId = 106 And EveLngBibId = 268 And HisLngBibId = 267
                     And ParStrIndex = 'RES' And 
                     And EveDatRedaction = EveDatRealisation
                then 1 else 0
           end) as NbreIncidentPrisEnDirect
FROM T_Evenement as TE inner join
     T_Historique
     on HisLngEveId = EveLngId join
     T_Param as TPA
     on TE.EveLngResponsableId = TPA.ParLngId
WHERE year(EveDatRedaction) = '2013'
group by MONTH(EveDatRedaction);

缺点是这不会使用where子句的索引。