Microsoft SQL 基于 2 列的服务器条件加入

Microsoft SQL Server Conditional Joining based on 2 columns

我想加入 3 个 tables,它们都具有相同的数据,除了一列是不同的名称(3 个 tables 中的每一个的日期不同)。三个 table 如下所示。目标是如果条件存在于 table 1 AND/OR table 2 确定条件是否存在于 table 3 对于每个人 id/condition。我目前正在加入 table 2 到 table 1,但我知道这没有考虑 table 2 中是否存在 table 中不存在的条件没有被考虑在内,无论如何,对此的任何帮助都是有用的。

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

谢谢!

如果你的数据库支持full join,你可以这样做:

select
    id,
    place,
    t1.condition_2018,
    t2.condition_2019,
    t3.condition_2020
from table1 t1
full join table2 t2 using(id, place)
full join table3 t3 using(id, place)

否则就复杂一点:union all 聚合是一种方法:

select 
    id, 
    place, 
    max(condition_2018) condition_2018,
    max(condition_2019) condition_2019,
    max(condition_2020) condition_2020
from (
    select id, place, condition_2018, null condition_2019, null condition 2020 from table1
    union all
    select id, place, null, condition_2019, null from table2
    select id, place, null, null, condition_2020 from table3
) t
group by id, place

这个怎么样(SQL 服务器语法)...

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

您似乎想要表 3 中的所有内容和其他两个表中的匹配项。那只是 left joins:

select t3.id, t3.place,
       t1.condition_2018, t2.condition_2019, 
       t3.condition_2020
from table3 t3 left join
     table2 t2
     on t3.id = t2.id and t3.place = t2.place left join
     table1 t1
     on t3.id = t1.id and t3.place = t1.place;

您需要一个 full outer jointable1table2 以及一个 left jointable3:

select 
  coalesce(t1.id, t2.id) id,
  coalesce(t1.place, t2.place) place,
  t1.Condition_2018,
  t2.Condition_2019,
  t3.Condition_2020
from table1 t1 full outer join table2 t2
on t2.id = t1.id
left join table3 t3
on t3.id = coalesce(t1.id, t2.id)

参见demo
结果:

>  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