我有以下数据
表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 :(得分:0)
您需要获得TransID
和Ref_Entity
的独特组合,然后在LEFT JOIN
上执行Table2
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;