SQL Server加入具有相同列名

时间:2017-08-26 22:32:59

标签: sql sql-server database sql-server-2008

我有3个数据库表,表A,表B,表C.表B和表C是不同的名称,并且具有相同的列名,而表C有两列多来自表b和表C行的数据可以是比表B更多。

Table A
-----------------------------------
ContractNo  | Contact
-----------------------------------
001         | AAA

Table B
---------------------------
ID  | ContractNo | Column A 
---------------------------
1   | 001        | Info A1
2   | 001        | Info A2

Table C 
---------------------------------------
ID  | ContractNo | Column A | Column B 
---------------------------------------
6   | 001        | Info A1   | Info AA1
7   | 001        | Info A2   | Info AA2
8   | 001        | Info A3   | Info AA3

当我查询时:

SELECT * FROM tableA as A 
INNER JOIN tableB AS B ON A.ContractNo = B.ContractNo 
INNER JOIN tableC AS C ON A.ContractNo = C.ContractNo
WHERE A.ContractNo = '001'

结果:

-----------------------------------------------------------------------------
ContractNo  | Contact | ID | Column A | ID | ContractNo | Column A | Column B
-----------------------------------------------------------------------------
001         | AAA     | 1  | Info A1  | 6  | 001        | Info A1  | Info AA1
001         | AAA     | 1  | Info A1  | 7  | 001        | Info A2  | Info AA2
001         | AAA     | 1  | Info A1  | 8  | 001        | Info A3  | Info AA3
001         | AAA     | 2  | Info A2  | 6  | 001        | Info A1  | Info AA1
001         | AAA     | 2  | Info A2  | 7  | 001        | Info A2  | Info AA2
001         | AAA     | 2  | Info A2  | 8  | 001        | Info A3  | Info AA3

预期结果:

ContractNo  | Contact | ID    | Column A | ID | ContractNo | Column A | Column B
-----------------------------------------------------------------------------
001         | AAA     | 1     | Info A1  | 6  | 001        | Info A1  | Info AA1
001         | AAA     | 2     | Info A2  | 7  | 001        | Info A2  | Info AA2
001         | AAA     | NULL  | NULL     | 8  | 001        | Info A3  | Info AA3

如果表B中有3行数据,ContractNo ='001',表C中有4行,ContractNo ='001',那么我得到了12行。预期结果为4行。

2 个答案:

答案 0 :(得分:0)

那是因为您可能想尝试close_date ...

这是一个片段

Coalesce

你应该能够适应它,得到你想要的结果!

答案 1 :(得分:0)

根据您的样本数据

SELECT A.contractno,
       A.contractno,
       B.id,
       B.[column a],
       C.id,
       C.contractno,
       C.[column a],
       C.[column b]
  FROM [Table A] A
  LEFT OUTER JOIN [Table C] C
    ON A.ContractNo = C.ContractNo
  LEFT OUTER JOIN [Table B] B
    ON B.ContractNo = C.ContractNo
   AND B.[column a] = C.[column a]

结果

contractno  contact id      column a    id  contractno  column a    column b
001         AAA     1       Info A1     6   001         Info A1     Info AA1
001         AAA     2       Info A2     7   001         Info A2     Info AA2
001         AAA     NULL    NULL        8   001         Info A3     Info AA3