Search code examples
sqlsql-serverleft-joinunionfull-outer-join

Microsoft SQL Server Conditional Joining based on 2 columns


I am looking to join 3 tables, all with the same data except one column is a different name (different date for each of the the 3 tables). The three tables look like the following. The goal is if a condition exists in table 1 AND/OR table 2 determine if a condition does or does not exist in table 3 for each individual id/condition. I'm currently left joining table 2 to table 1 but I'm aware that is not accounting for if a condition in table 2 exists that is not in table it is not being accounted for, anyways, any help would into this would be useful.

Table 1
    id  place Condition_2018 
    123  ABC  flu
    456  ABC  heart attack

Table 2
    id  place Condition_2019
    123  ABC  flu
    789  def  copd
Table 3
    id  place Condition_2020
    456  ABC  heart attack
    789  def  copd
    123  ABC  flu
OUTPUT:
Table 2
    id  place Condition_2018  Condition_2019  Condition_2020
    123  ABC  flu             flu             flu
    456  ABC  heart attack    null            heart attack
    789  def  NULL            copd            copd

Thank you!


Solution

  • How about this (SQL Server syntax)...

    SELECT 
        x.id
      , x.place
      , x.Condition_2018
      , x.Condition_2019
      , t3.Condition_2020 
    FROM (
            SELECT 
                COALESCE(t1.id, t2.id) AS id
              , COALESCE(t1.place, t2.place) AS place
              , t1.Condition_2018
              , t2.Condition_2019
            FROM Table1 AS t1 
            FULL OUTER JOIN Table2 AS t2 ON t1.id = t2.id AND t1.place = t2.place
        ) AS x LEFT JOIN Table3 AS t3 ON x.id = t3.id AND x.place = t3.place