左连接没有给出所有记录我的查询错误

时间:2015-08-28 11:15:52

标签: sql-server tsql

当我执行左外连接时,我希望得到所有记录,查询将返回左表中与右表不匹配的所有记录。

我想选择记录,即使表中没有月份数据。假设我有一个五个月的记录。因此,当我执行我的查询时,我希望从右表[client_service]表中获得总共12个记录[左外连接]和0值。

我的查询

SELECT  YEAR(CLIENT_SERVICE.cliserv_effective_date) As Year
        , MonthsTable.MonthName As Month
        , COUNT(CLIENT_SERVICE.cliserv_id) As ClientsInService 
FROM    MonthsTable
        left outer join CLIENT_SERVICE
         ON MonthsTable.MonthName = DATENAME(month,CLIENT_SERVICE.cliserv_effective_date)
WHERE   CLIENT_SERVICE.serv_id = 24
        AND CLIENT_SERVICE.cliserv_status = 'Active' 
        AND YEAR(CLIENT_SERVICE.cliserv_effective_date) BETWEEN 2014  AND 2015 
GROUP BY YEAR(CLIENT_SERVICE.cliserv_effective_date)
        , DATENAME(month,CLIENT_SERVICE.cliserv_effective_date)
        , [MonthsTable].MonthName
        , MONTH(CLIENT_SERVICE.cliserv_effective_date)  
ORDER BY YEAR(CLIENT_SERVICE.cliserv_effective_date)
        , MONTH(CLIENT_SERVICE.cliserv_effective_date);

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

在where子句中有右表的列。把它放在on子句中:

SELECT YEAR(CLIENT_SERVICE.cliserv_effective_date) As Year,
MonthsTable.MonthName As Month, COUNT(CLIENT_SERVICE.cliserv_id) As ClientsInService 
FROM MonthsTable left outer join  CLIENT_SERVICE ON MonthsTable.MonthName = DATENAME(month,CLIENT_SERVICE.cliserv_effective_date) and CLIENT_SERVICE.serv_id = 24 
 AND CLIENT_SERVICE.cliserv_status = 'Active' 
AND YEAR(CLIENT_SERVICE.cliserv_effective_date) BETWEEN 2014  AND 2015 
GROUP BY YEAR(CLIENT_SERVICE.cliserv_effective_date), DATENAME(month,CLIENT_SERVICE.cliserv_effective_date), 
[MonthsTable].MonthName,MONTH(CLIENT_SERVICE.cliserv_effective_date)  
ORDER BY YEAR(CLIENT_SERVICE.cliserv_effective_date), 
MONTH(CLIENT_SERVICE.cliserv_effective_date)