加入两个表中的数据

时间:2013-08-20 09:39:37

标签: sql-server left-join

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

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时,我不显示 Null 0 但跳过它。为了管理它,我创建了一个Calendar表,如下所示:

enter image description here

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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