在SQL Server 2012中,我需要查询为 where 子句中的每个元素返回一个值。
select count(id) idCount, squad from dbo.Project
where id between 60000 and 80000
and status = ('Complete') and squad in ('Mechanical', 'Civil', 'Electrical', 'Architectural')
and fiscalyear = 2018
group by squad
order by squad asc
查询返回
idCount Squad
1 Civil
3 Electrical
3 Mechanical
我希望输出是什么
idCount Squad
0 Architectural
1 Civil
3 Electrical
3 Mechanical
答案 0 :(得分:2)
您需要left join
。在SQL Server中,您可以执行以下操作:
select count(p.id), v.squad
from (values ('Mechanical'), ('Civil'), ('Electrical'), ('Architectural')
) v(squad) left join
dbo.Project p
on v.squad = p.squad and
p.id between 60000 and 80000 and
p.fiscalyear = 2018
group by v.squad
order by v.squad asc ;
请注意,所有where
条件都需要放在on
子句中,以防止无意中过滤不匹配的值。