2017-09-13 25 views
0

我有2个表如下 -匹配2个表有多个重复的值在SQL

表1 -

Catalog Number| Section| Qty|  Status 
--- 
123|    A|   3|  New 
--- 
123|    B|   2|  New 
--- 
123|   C|   1|  New 
--- 
456|    A|   3|  Old| 
--- 
456|    B|   1|  Old| 
-- 
456|    C|   2|   Old| 
-- 

表2:

Catalog Number| Section| Qty|  Status 
--- 
123|    A|   3|  New 
--- 
123|   B|   2|  New 
--- 
123|    C|   1|  New 
--- 
123|   D|   3|  New 
--- 
456|   A|   3|  Old 
--- 
456|    B|   1|   Old 
--- 

我想要的结果是什么像这样 -

Catalog Number| Section| Qty| Status| Catalog Number| Section| Qty| Status| 
--- 
123|   A|   3|  New|  123|   A|  3| New 
--- 
123|   B|  2|  New|  123|   B|  2| New 
--- 
123|   C|   1|  New|  123|   C|  1| New 
--- 
Null|   Null|  Null|  Null| 123|  D|  3| New 
--- 
456|    A|   3|  Old|  456|  A|  3| Old 
--- 
456|    B|   1|   Old|  456|  B|  1| Old 
--- 
456|    C|   2|   Old|  Null|  Null| Null| Null 
--- 

我曾尝试使用SQL联接,并没有得到任何地方。任何帮助将不胜感激。谢谢!!

编辑 -

这是我使用的查询:

SELECT * 
FROM Table1 a 
INNER JOIN Table2 b ON a.CatalogNumber = b.CatalogNumber 
+1

这两个表之间的关系是什么? –

+0

你可以发布不工作的SQL,以便我们提供建议。 –

+0

@KalharaAmarasinghe'Catalog Number'是我用来加入2个表的列,如果这是你要求的 –

回答

2

您是否在寻找一个FULL OUTER JOIN?

SELECT a.CatlogNumber, 
a.Section, 
a.Qty, 
a.Status, 
b.CatlogNumber, 
b.Section, 
b.Qty, 
b.Status 
FROM Table1 a 
FULL OUTER JOIN Table2 b ON a.CatalogNumber = b.CatalogNumber; 

这将显示每个表中的记录和NULL值,其中表中没有另一个表中的等效记录。

1

您可以使用完全外部联接。查询如下,

SELECT Table1.CatlogNumber, 
Table1.Section,Table1.Qty,Table1.Status,Table2.CatlogNumber, 
Table2.Section,Table2.Qty,Table2.Status, 
FROM Table1 
FULL OUTER JOIN Table2 ON Table1.CatlogNumber=Table2.CatlogNumber 
ORDER BY Table1.CatlogNumber; 
1

我相信你需要执行2个单独的查询的联盟。像这样的东西也许

declare @table1 table(CatalogNumber int,Section varchar(100), Qty int, Status varchar(100)) 
declare @table2 table(CatalogNumber int,Section varchar(100), Qty int, Status varchar(100)) 
INSERT INTO @table1 
SELECT 123, 'A', 3, 'New' 
UNION SELECT 123, 'B', 2, 'New' 
UNION SELECT 123, 'C', 1, 'New' 
UNION SELECT 456, 'A', 3, 'Old' 
UNION SELECT 456, 'B', 1, 'Old' 
UNION SELECT 456, 'C', 2, 'Old' 

INSERT INTO @table2 
SELECT 123, 'A', 3, 'New' 
UNION SELECT 123, 'B', 2, 'New' 
UNION SELECT 123, 'C', 1, 'New' 
UNION SELECT 456, 'D', 3, 'Old' 
UNION SELECT 456, 'A', 3, 'Old' 
UNION SELECT 456, 'B', 1, 'Old' 


SELECT t1.*, t2.*FROM @table1 t1 LEFT JOIN @table2 t2 ON t1.CatalogNumber = t2.CatalogNumber and t1.Section=t2.Section and t1.Qty=t2.Qty and t1.Status=t2.Status 
UNION 
SELECT t1.*, t2.*FROM @table2 t2 LEFT JOIN @table1 t1 ON t1.CatalogNumber = t2.CatalogNumber and t1.Section=t2.Section and t1.Qty=t2.Qty and t1.Status=t2.Status