Sql 联接查询以合并两个表
我希望查询从数据库中的两个表中获取输出,如下所示Sql 联接查询以合并两个表,sql,sql-server,Sql,Sql Server,我希望查询从数据库中的两个表中获取输出,如下所示 table1-cities ----> ------------- Table2----> ------------------------- | City | | Person | City | ------------- ---------------
table1-cities ----> ------------- Table2----> -------------------------
| City | | Person | City |
------------- -------------------------
| Delhi | | Bob | Delhi |
| Mumbai | | Alice | Delhi |
| Pune | | Tim | Pune |
------------- -------------------------
Output----> ---------------------------
| City | No.of persons |
---------------------------
| Delhi | 2 |
| Mumbai | 0 |
| Pune | 1 |
----------------------------
我试过了,但没有得到正确的输出
那我该怎么办
提前谢谢
真诚的。试试这个
select t1.city,
Count(t2.city)
from table1 t1
left join table2 t2 on t2.city=t1.city
group by t1.city
请尝试以下代码:
Select c.city, COUNT(p.city) As 'No.of persons' from #cities c
Inner join #perrson p on c.city= p.city
group by c.city
对于所有零值,请使用左连接
Select c.city, COUNT(p.city) As 'No.of persons' from #cities c
Left join #perrson p on c.city= p.city
group by c.city
试试这个
select c.City,
count(p.City) as Number_OF_Persons
from City as c
left Join Person as p on c.City = p.City
group by c.City
两件事:
- 尽可能使用
作为主键李>Id
- 在Person表中创建一个外键约束,该表引用
表(Id)李>城市
Select
c.city,
COUNT(p.cityId) "NoOfPerson"
from
TabCity c
left join TabPerson p on c.Id= p.cityId
group by
c.city
这里,
cityId
是TabPerson
表中的外键列,c.Id
是TabCity
表中的主键列,只要不添加可能改变匹配行数的条件,就可以在联接之前进行计数,这通常更有效:
Select
c.City,
COALESCE(p.cnt, 0) "No.of persons" -- change NULL to zero for missing cities
from cities c
left join
(
Select City, count(*) as cnt
From persons
Group by City
) p
on c.City= p.City
试试这个:
Select City, Sum(Cnt) as NoOfPersons From
(Select City, count(*) as Cnt from Table1
Group By City
Union
Select City, count(*) as Cnt from Table2
Group By City)
Group By City
我尝试了“选择城市,从表2中按城市分组计数(城市)”—
这没关系,但不容易阅读。由于您希望按城市统计记录,所以应该这样说:count(*)
。这个查询当然不会显示,因为它不在表中。为了显示孟买,您必须在查询中包含cities表。最简单的方法是根本不连接表,只需再选择所需的计数:
select city, (select count(*) from table2 where table2.city = table1.city) as no_of_persons
from table1;
这将显示孟买计数为空。如果希望为零,请使用合并:
select
city,
coalesce((select count(*) from table2 where table2.city = table1.city),0) as no_of_persons
from table1;
如其他人所示,您还可以将表2连接到表1,然后进行分组和计数。但是,正如您已经看到的,这很容易出错,因为您必须使用
count(个人)
(或count(城市)
),而不是像计数记录时通常使用的那样使用count(*)
,以便不计数外部连接的记录。显示您当前的查询!(您是否按分组?)另外,为什么要将城市名称存储在两个不同的表中?请阅读左连接
、计数
和分组方式
。我尝试了“从表2中按城市分组选择城市,计数(城市)”,这将为孟买生成1。您需要为COUNT.No参数指定一列Table2
。这给了你3个德里(1个是因为它是一个城市+2个城市中的两个人)。这不是UNION适合的查询,表1中的GROUP BY on city也没有任何意义,因为这是cities表,它应该只保存每个城市一次。