I have a Table "C" that is meant to interlink two other tables, Table A and Table B. They have the general forms:
Table A:
| Id | Value |
| ------------ | ------------ |
| 1 | 10 |
| 2 | 20 |
| 3 | 30 |
Table B:
Id | Value |
---|---|
1 | 4 |
2 | 6 |
3 | 8 |
Table C has two columns that are either NULL or a foreign key for tables A or B.
Table C:
| Key | Table_A_Id | Table_B_Id |
| ------------ | ------------ | ------------ |
| 1 | 1 | NULL |
| 2 | NULL | 2 |
| 3 | 2 | NULL |
| 4 | NULL | 1 |
Is there a way to join these tables together such that the output is:
Key | Value |
---|---|
1 | 10 |
2 | 6 |
3 | 20 |
4 | 4 |
When I have had these issues in the past I have usually run two separate queries and post-processed the data in R, but I was curious if there is a way that this can be done natively in SQL. If I just LEFT JOIN Tables A and B to C then it would create two different Value columns.
1条答案
按热度按时间6mzjoqzu1#
When asking questions, it's really helpful to provide the DDL/DML, in addition to the example data:
Using that:
What are we doing here? TableC is the common table, from there we can
LEFT OUTER JOIN
the other two tables, so we get rows back whether there is a match or not. Then, weCOALESCE
(take the first non-null value, alternativelyISNULL
) each of the value columns with a literal 0 and add the results together. Finally, we return the[Key]
column (in braces as it's a reserved word) and the result of theCOALESCE
for each row inTableC
.