SQL在"WHERE IN()"子句中显示COUNT的所有值

Mar*_*usP 2 sql t-sql sql-server

我有以下查询:

select postal_code, count(postal_code) as c
from postal_codes
where postal_code in ('A0A 0A1', 'A0A 0A2', 'A0A 0A3', 'A0A 0A4', 'A0A 0B1', 'A0A 1B1', 'A0A 1B2')
group by postal_code
Run Code Online (Sandbox Code Playgroud)

数据库中不存在最后两个值('A0A 1B1','A0A 1B2'),因此不会显示它们.我希望它们显示,COUNT()值为0.

查询将只向我显示计数为1的前5个,但我需要全部7个,最后两个的计数为0.

那可能吗?

基本上我有一个值列表(使用"WHERE IN()"),我需要检查它们是否存在于数据库中.

谢谢!

Yog*_*rma 5

您可以使用VALUES构造并执行以下操作LEFT JOIN:

select t.postal_code, count(p.postal_code) as c
from ( values ('A0A 0A1'), ('A0A 0A2'), ('A0A 0A3'), ('A0A 0A4'), ('A0A 0B1'), ('A0A 1B1'), ('A0A 1B2') 
     ) t(postal_code) left join
     postal_codes p
     on p.postal_code = t.postal_code
group by t.postal_code;
Run Code Online (Sandbox Code Playgroud)