2017-09-13 66 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