即使where子句删除了那些结果,如何显示连接的结果

时间:2011-09-06 15:23:46

标签: sql

我有一个连接到Counties表的查询。该表包含14个不同的县。我在一定时间内计算每个县的成员人数。当我选择的那段时间不包括来自某个县的任何成员时,无论我是否使用右连接或内连接到县表,该县都不会显示。我的目标是,如果没有一个成员从一个县返回,则显示该县的总数为0。我该怎么做?

SELECT DISTINCT
    e.County,
    COUNT(DISTINCT d.MemberID) AS TotalUniqueProviders
FROM
    dw.FactMedicalClaimLine a
INNER JOIN 
    dw.DimMember d
ON
    a.MemberKey = d.MemberKey
RIGHT JOIN
    dw.DimGeography e
ON
    a.GeographyKey = e.GeographyKey
WHERE
    LEFT(ServiceDate, 6) >= 201001
    AND LEFT(PaidDate, 6) BETWEEN 201010 AND 201012

2 个答案:

答案 0 :(得分:2)

将您的过滤器移至JOIN子句

RIGHT JOIN
    dw.DimGeography e
ON
    a.GeographyKey = e.GeographyKey
AND
    LEFT(ServiceDate, 6) >= 201001
    AND LEFT(PaidDate, 6) BETWEEN 201010 AND 201012

由于OUTER JOIN而保留的国家/地区行NULLServiceDatePaidDate,因此最终会被WHERE条款排除。< / p>

您在查询的发布版本中似乎也错过了GROUP BY e.GeographyKey,而DISTINCT GROUP BY则不需要{{1}}。

答案 1 :(得分:1)

WHERE替换为AND,即:

ON     a.GeographyKey = e.GeographyKey 
AND    LEFT(ServiceDate, 6) >= 201001     
AND LEFT(PaidDate, 6) BETWEEN 201010 AND 201012