我有一条SQL语句:
SELECT
p.id
,SUM(CASE WHEN pf.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM people p
inner JOIN people_facilities pf ON p.ID = pf.ID
group by p.id
从上面的陈述中,您将了解到facility_count不能大于3。但是,列表中的第一个有18个设施。
为什么这个计数不起作用?
答案 0 :(得分:1)
如果要计算个不同工具的数量,请使用count(distinct)
:
SELECT p.id,
COUNT(DISTINCT CASE WHEN pf.facility_code in ('S','H','E') THEN pf.facility_code END) as facility_count
FROM people p JOIN
people_facilities pf
ON p.ID = pf.ID
GROUP BY p.id;
您的查询可疑。我希望JOIN
更像pf.PeopleID = p.id
。
如果没有,则可以通过删除JOIN
来简化此查询,因为您要汇总的ID
在people_facilities
表中。我还怀疑条件可以移至WHERE
子句:
SELECT pf.id, COUNT(DISTINCT pf.facility_code) as facility_count
FROM people_facilities pf
WHERE pf.facility_code IN ('S', 'H', 'E')
GROUP BY pf.id;
答案 1 :(得分:1)
联接后,可能存在多个行,这些行具有相同的id
和相同的facility_code
。
因此,首先获取这些列的不同对,然后进行分组和汇总:
SELECT
t.id,
SUM(CASE WHEN t.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM (
SELECT DISTINCT p.id, pf.facility_code
FROM people p inner JOIN people_facilities pf
ON p.ID = pf.ID
) t
group by t.id