加入缺失的记录

时间:2018-02-12 16:39:29

标签: sql amazon-redshift

对于以下数据集(超简化):

表1

SQL> select
  2    listagg(s.department_name, ',') within group (order by null) result
  3  from departments s, departments d;
from departments s, departments d
     *
ERROR at line 3:
ORA-01489: result of string concatenation is too long


SQL>
SQL> select
  2  rtrim(xmlagg(xmlelement (e, s.department_name || ',')).extract
  3    ('//text()').getclobval(), ',') result
  4  from departments s, departments d;

RESULT
--------------------------------------------------------------------------------
Administration,Administration,Administration,Administration,Administration,Admin

SQL>

表2

ext_id, actions
z1,     100
z2,     100
x1,     200
x2,     200

我这样加入他们:

tid, aid, eid, aum
1,   a,   z1,  100
1,   b,   z2,  100
1,   c,   z3,  100
2,   d,   x1,  200
2,   e,   x2,  200
2,   f,   x3,  200

这会为表格create table #temp as select a.*, tid, aid, aum from #t a join #t2 b on a.ext_id=b.eid 提供#temp中与#t2匹配的所有记录,并映射其中包含的其他字段。

我现在要将#t1#temp(单独的查询)进行匹配,并获取基于{{1}加入的其余#t2的所有数据}:

即。输出应该是:

aid

谢谢

1 个答案:

答案 0 :(得分:1)

使用外部联接。我会这样做:

select a.*, tid, aid, aum
from @t2 b left join
     #t a
    on a.ext_id = b.eid
where a.ext_id is null;