2017-07-18 63 views
0

我有以下數據連接兩個表沒有PK

表1

TransID | Ref_Entity | Amount 
--------+------------+-------- 
null | DEPOSIT | 0.00 
null | BANKCHARGES| 0.00 
null | OTHERS  | 0.00 

表2

TransID | Ref_Entity | Amount 
--------+------------+--------- 
1  | DEPOSIT | 100.00 
1  | BANKCHARGES| 100.00 
2  | OTHERS  | 150.00 

,並希望有這樣的輸出:

1 | DEPOSIT | 100.00 
1 | BANKCHARGES| 100.00 
1 | OTHERS  |  0.00 
2 | DEPOSIT |  0.00 
2 | BANKCHARGES|  0.00 
2 | OTHERS  | 150.00 

我試過了:

SELECT 
    * (SELECT '' AS TransID, Ref_Entity, 0.00 AS Amount 
     FROM TABLE1 
     UNION 
     SELECT TransID, Ref_Entity, Amount 
     FROM TABLE2 
    ) 

感謝您的幫助。

+0

這最後一排'1 |其他| | 150.00'應該是'2 |其他| | 150.00「對嗎? –

+0

@NenadZivkovic,對。我已經修改了它。謝謝。 – angel

回答

0

你需要得到的TransIDRef_Entity的不同組合,然後做一個LEFT JOINTable2

WITH Combinations(TransID, Ref_Entity) AS(
    SELECT 
     t2.TransID, t1.Ref_Entity 
    FROM (SELECT DISTINCT Ref_Entity FROM Table1) t1 
    CROSS JOIN (SELECT DISTINCT TransID FROM Table2) t2 
) 
SELECT 
    c.TransID, 
    c.Ref_Entity, 
    Amount = ISNULL(t2.Amount, 0) 
FROM Combinations c 
LEFT JOIN Table2 t2 
    ON c.TransID = t2.TransID 
    AND c.Ref_Entity = t2.Ref_Entity; 

ONLINE DEMO

+0

它可以工作,但如果表格的列數不同,它是否合適?我嘗試添加更多的列/字段名稱(對於Table2),並且它說列名是無效的。 – angel

+0

對不起。我應該在「Select distinct」查詢中添加其他字段。 – angel

+0

@angel對不起,我在Cte中加了'DISTINCT'。 –