我需要在2个不同的表上计算城市出现的次数。一个表是供应商表,其中包含vendor_id,城市和州。第二个表是具有消费者ID,城市和州的消费者。我的查询需要返回名称匹配的州,供应商城市的城市数和消费城市的数目。
我已经尝试了几种不同的方法,例如相交和并集,但都无法做到。我的最新文章在下面,但不确定我在做什么错
SELECT S.State
,C.City
,count(S.City) as Number_Of_Suppliers
,count(C.City) as Number_Of_Consumers
from dbo.Tb_Supplier S
left outer Join dbo.Tb_Consumer C
On S.STATE = C.STATE
AND S.City = C.City
group by S.state
,C.City
答案 0 :(得分:0)
使用union all
和group by
:
select state, city, sum(supplier)
sum(supplier) as Number_Of_Suppliers,
sum(consumer) as Number_Of_Consumers
from ((select state, city, 1 as supplier, 0 as consumer
from dbo.Tb_Supplier s
) union all
(select state, city, 0 as supplier, 1 as consumer
from dbo.Tb_Consumer c
)
) sc
group by state, city