在联接表的列上使用isull

时间:2018-07-03 18:01:59

标签: sql sql-server tsql

我有以下2张桌子:

 city_code  city_name
    1   Berlin
    2   Munich
    3   Bonn
    4   Frankfurt

city_code   Customer_number
1   A
2   B
1   C
1   D
3   E

以下代码可以正常工作,它为我提供了每个城市的客户数量,但是由于没有客户,它为法兰克福提供了空值:

select c.cityName, c.cityCode, isnull(s.customerCount,0)
from cities as c
left join
(
select city_code, count (customerNumber) as CustomerCount
from subscribers
group by city_code
) as s
on c.cityCode = s.city_code
group by cityName;

现在我想做同样的事情,但是显示0而不是null。为此,我使用了相同的代码,但将第一行更改为:

select c.cityName, c.cityCode, isnull(s.customerCount,0)

这不起作用。我正在在线环境(w3schools)上工作,该环境未指定错误,仅指示存在错误。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

为什么使用subquery,您可以直接执行JOIN

select c.city_name, c.city_code, count(s.customer_number) as CustomerCount
from cities c left join 
     subscribers s
     on s.city_code = c.city_code
group by c.city_name, c.city_code;