SQL需要获得零值的结果

时间:2015-06-16 15:24:33

标签: sql

我有一个带有cityName和peopleName作为两个列名的表CITY_PEOPLE和另一个带有peopleName和aliveStatus列名的表PEOPLE_ALIVE

aliveStatus可以有Y或N

我希望得到这个城市和城市名称的人数

通过以下查询,我可以获得计数,如果计数> 0

SELECT cityName, count(*) noOfPeopleAlive 
FROM CITY_PEOPLE b 
WHERE peopleName in (SELECT peopleName FROM PEOPLE_ALIVE where aliveStatus='Y') 
GROUP BY b.cityName

但是我想要计数= 0的城市列表。我该怎么办?

3 个答案:

答案 0 :(得分:1)

使用Left Join

SELECT cityName, count(p.peopleName) noOfPeopleAlive 
FROM CITY_PEOPLE b 
LEFT JOIN PEOPLE_ALIVE p
ON p.peopleName = b.peopleName
AND p.aliveStatus = 'Y'
group by b.cityName

另请注意:只要明白你的问题,如果你加入了一个人的名字,那么同名的人会让你的生活变得困难,这是很常见的。

答案 1 :(得分:1)

左外连接将解决您的问题

SELECT cityName, count(*) noOfPeopleAlive 
FROM CITY_PEOPLE b 
LEFT OUTER JOIN PEOPLE_ALIVE p
ON p.peopleName = b.peopleName
AND p.aliveStatus = 'Y'
GROUP BY b.cityName

答案 2 :(得分:1)

奇怪的表结构,但这将起作用:

select
    C.cityName,
    noOfPeopleAlive = sum(case P.aliveStatus when 'Y' then 1 else 0 end)
from
    CITY_PEOPLE C
    left join PEOPLE_ALIVE P on C.peopleName = P.peopleName
group by
    C.cityName;