Reputation: 105
Suppose I have Table1(A, B, C), and Table2(B)
Table1:
A | B | C
------------------------
a1 b1 c1
a1 b2 c2
a2 b1 c3
Table2:
B
--
b1
b2
b3
b4
The result I want:
A | B | C
-------------------
a1 b1 c1
a1 b2 c2
a1 b3 [some default value]
a1 b4 [some default value]
a2 b1 c3
a2 b2 [some default value]
a2 b3 [some default value]
a2 b4 [some default value]
How can I do this?
Essentially I need a way to right outer join table1 with table2, but "group by" column A.
Upvotes: 0
Views: 63
Reputation: 147266
You can achieve your desired result by CROSS JOIN
ing the distinct values of A
from Table1
with the values of B
from Table2
and then LEFT JOIN
ing to Table1
again to get the corresponding C
values, using COALESCE
to supply a default value where there is no matching C
value:
SELECT t1.A, t2.B, COALESCE(t3.C, 'c0') AS C
FROM (SELECT DISTINCT A
FROM Table1) t1
CROSS JOIN Table2 t2
LEFT JOIN Table1 t3 ON t3.A = t1.A AND t3.B = t2.B
Output:
a b c
a1 b1 c1
a1 b2 c2
a1 b3 c0
a1 b4 c0
a2 b1 c3
a2 b3 c0
a2 b2 c0
a2 b4 c0
Upvotes: 3