我有一个连接到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
答案 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
而保留的国家/地区行NULL
和ServiceDate
将PaidDate
,因此最终会被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