2

在我的项目中,公司的客户正在打电话询问他们的设备。每次拨打电话时,都会将其保存在数据库中。现在我需要知道公司在特定年份每个月接到多少电话,所以我写了这个请求:

SELECT COUNT(EveLngId) FROM T_Evenement
where EveLngDosId = 1062
And EveLngBibId = 268
And EveTinSite = 1
And EveLngEleId <> 17432
And (EveTinParEmail is null OR EveTinParEmail = 0)
And (EveLngTicketTransfertId IS NULL OR EveLngTicketTransfertId = 0)
And (EveTinIncidentAnnulation is null or EveTinIncidentAnnulation=0)
And YEAR(EveDatRedaction) = 2013
group by MONTH(EveDatRedaction)

该请求有效,但问题是当一个月的值为 null 时,我不会显示Null0,但会跳过它。为了管理它,我创建了一个日历表,如下所示:

在此处输入图像描述

所以现在我需要加入这两个表以获得每个月的值,但我可以弄清楚如何做到这一点。有什么建议或解决方案吗?

4

2 回答 2

3
;WITH ResultsCTE AS
(
    SELECT MONTH(EveDatRedaction) AS ResultMonth,
           COUNT(EveLngId) AS ResultCount 
    FROM   T_Evenement
    where  EveLngDosId = 1062
           And EveLngBibId = 268
           And EveTinSite = 1
           And EveLngEleId <> 17432
           And (EveTinParEmail is null OR EveTinParEmail = 0)
           And (EveLngTicketTransfertId IS NULL OR EveLngTicketTransfertId = 0)
           And (EveTinIncidentAnnulation is null or EveTinIncidentAnnulation=0)
           And YEAR(EveDatRedaction) = 2013
    GROUP BY MONTH(EveDatRedaction)
)
SELECT CalendarStrLibelle,ISNULL(ResultCount,0) AS ResultCount
FROM   Calendar 
       LEFT JOIN ResultsCTE 
          ON ResultMonth = CalendarLngId
于 2013-08-20T09:43:58.250 回答
2

试试这个——

SELECT  CalendarStrLibelle
    ,   ResultCount = ISNULL(cnt, 0) 
FROM dbo.Calendar c
LEFT JOIN (
    SELECT 
          [month] = MONTH(EveDatRedaction) 
        , cnt = COUNT(EveLngId) 
    FROM dbo.T_Evenement
    WHERE EveLngDosId = 1062
        AND EveLngBibId = 268
        AND EveTinSite = 1
        AND EveLngEleId <> 17432
        AND ISNULL(EveTinParEmail, 0) = 0
        AND ISNULL(EveLngTicketTransfertId, 0) = 0
        AND ISNULL(EveTinIncidentAnnulation, 0) = 0
        AND YEAR(EveDatRedaction) = 2013
    GROUP BY MONTH(EveDatRedaction)
) t ON t.[month] = c.CalendarLngId
于 2013-08-20T09:55:21.667 回答