我有以下查询:
SELECT
f.name,
COUNT(distinct(p.id))
FROM
problems p INNER JOIN problem_list pl on p.problem_list_id = pl.id
FULL OUTER JOIN facilities f on f.id = p.facility
WHERE
p.problem_list_id = '100'
AND f.name in ('CRJ','TVRJ','WRJ')
GROUP BY
f.name
ORDER BY
f.name
运行此查询时,有时其中一个facilities
不会返回结果。在这种情况下,我仍然希望我的结果集显示该设施,但返回0。
例如:
CRJ | 0|
TVRJ | 12|
WRJ | 2|
我已尝试使用coalesce
,并在facility
表格上调整我的联接,但它似乎无法正常工作。
答案 0 :(得分:3)
我认为不需要FULL JOIN
,只需LEFT JOIN
:
SELECT
f.name,
ISNULL(COUNT(DISTINCT p.id),0) N
FROM
facilities f
LEFT JOIN ( SELECT *
FROM problems
WHERE problem_list_id = '100') p
ON f.id = p.facility
LEFT JOIN problem_list pl
ON p.problem_list_id = pl.id
WHERE
f.name in ('CRJ','TVRJ','WRJ')
GROUP BY
f.name
ORDER BY
f.name;
答案 1 :(得分:1)
您的原始查询是以问题开头的,如果您想要包含那些您可能想要从设施开始出现问题的设施。
SELECT f.name, ISNULL(COUNT(DISTINCT p.id), 0)
FROM facilities f
LEFT JOIN problems p ON p.facility = f.id AND p.problem_list_id = '100'
LEFT JOIN problem_list pl ON pl.id = p.problem_list_id
WHERE f.name in ('CRJ', 'TVRJ', 'WRJ')
GROUP BY f.name
ORDER BY f.name