sql查询获取客户地址

时间:2019-03-27 14:05:44

标签: sql-server

我有两个表,即table Atable BTable B的主键为table A作为Id列。

我想从两个表中获取名称和地址。enter image description here

我该如何实现?

我尝试过:

select name,address from tableA join tableB on tableA.id=tableB.id

1 个答案:

答案 0 :(得分:0)

您自己的答案是正确的。

这是您描述的具有以下关系的表:

Your basic as ever table diagram

我在表中填充了一些guid,然后复制并粘贴了自己的SQL

  

(受影响的50行)

尝试一下 检查tableA是否有值

Select COUNT(*) from [tableA]

还有tableB

Select COUNT(*) from [tableB]

如果它们的计数都> 0 tableA中有多少项在tableB中具有至少一个值

--Show all the raw data
Select tableA.*,(select count(*) from tableB where tableA.id = tableB.id)VolumeOfAddresses
FROM tableA
--or Group and count it
Select VolumeOfAddresses,count(*) NameCount
FROM (Select tableA.*,(select count(*) from tableB where tableA.id = tableB.id)VolumeOfAddresses
FROM tableA) a
group by a.VolumeOfAddresses
--or express that as a string of text for simplicity
Select cast(count(*) as varchar(10)) + ' Names exists which each have an address COUNT of ' + cast(VolumeOfAddresses as varchar(10))A_TextString
FROM (Select tableA.*,(select count(*) from tableB where tableA.id = tableB.id)VolumeOfAddresses
FROM tableA) a
group by a.VolumeOfAddresses

测试中最后一个查询的示例结果显示:

  • 存在50个名称,每个名称的地址COUNT为0
  • 存在50个名称,每个名称的地址COUNT为1