【问题标题】:SQL coalesce - other ways to populate merged values in the resulting output?SQL 合并 - 在结果输出中填充合并值的其他方法?
【发布时间】:2020-02-11 16:32:16
【问题描述】:

我想加入两个表

have1
key ...
a   ...
b   ...
c   ...

have2
key ...
a   ...
c   ...
d   ...

并获得类似的输出

want
key ...
a   ...
b   ...
c   ...
d   ...

我知道

create table want as 
  select coalesce(a.key, b.key) as key, ..., 
  from have1 a full join have2 b 
  on a.key=b.key;

会给我输出,但有其他选择吗?我想要更简洁易读的代码,并且加入 3 或 4 个条件似乎需要大量文本才能实现所需的输出(例如,相对于 SAS 数据步骤)。

【问题讨论】:

  • 关键变量是唯一的公共变量吗?你试过NATURAL加入吗?

标签: sql sas full-outer-join


【解决方案1】:

你可以使用union all:

select h1.*
from have1 h1
union all
select h2.*
from h2
where not exists (select 1 from have1 h1 where h1.key = h2.key);

【讨论】:

    【解决方案2】:

    在许多数据库中,您可以使用 using 语法消除连接列的歧义:

    create table want as 
    select key, ..., 
    from have1 a 
    full join have2 b using (key)
    

    【讨论】:

      【解决方案3】:

      UNION 运算符是您想要的。它会自动删除重复项。

      data have1;
      input key $;
      cards;
      a
      b
      c
      ;;;;
      run;
      
      data have2;
      input key $;
      cards;
      a
      b 
      d
      ;;;;
      run;
      
      proc sql;
      create table want as 
      select * from 
      have1 union select * from have2;
      quit;
      
      proc print data=want;
      run;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多