寻求帮助:SQL Server在2个表中查询group by

时间:2011-08-05 14:41:03

标签: sql-server-2008

我有2张桌子

MEN

Fname | City
------------
A     | AA
B     | BB
C     | AA
D     | AA
E     | CC

市内

City
----
AA
BB
CC
DD
EE
FF

我需要一个查询来计算每个城市中每种类型的出现次数(包括不在主列表中的城市)

类似

City | Count
------------
AA   | 3
BB   | 1
CC   | 1
DD   | 0
EE   | 0
FF   | 0

标题

3 个答案:

答案 0 :(得分:2)

您需要正确的加入;

select 
    cities.city,
    count(men.city)
from
    men 
    right join cities on cities.city=men.city
group by cities.city

答案 1 :(得分:1)

如果您需要选择城市表中的所有列,则必须使用正确的连接。如果需要选择Men表中的所有列,请使用left join。

Select c.City, count(m.city)
From Men m
Right Join City c ON c.city = m.city
GroupBy c.city

答案 2 :(得分:1)

select C.City,
       count(M.Fname) as [Count]
from Citys as C
  left outer join MEN as M
    on C.City = M.City
group by C.City
order by C.City