Skip to content
Advertisement

Depending on column value, query different tables

I have table A where each IDENTIFIER value is unique. Depending on whether its CC or DC, I need to join it with different tables, for example if its “CC_” I need to map it to table B and if its “DC_” I need to map it to table C.

TABLE A:

TABLE B:

TABLE C:

I want the result to look like this:

First of all, how could I just get “1234567” from “CC_1234567” and second when writing a join query, I would get other columns in the final resulting table, such as B.INSTRUMENT, C.INSTRUMENT. Each IDENTIFIER in table A only maps to either table B OR table C.

Advertisement

Answer

You can left join twice, and then use coalesce() in the select clause:

If there are matches in both tables, the above query gives priority to tableb.

If you want to exclude rows that have no match in either tables, then you can add the following where clause:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement