SQL 连接两个表并创建新列

SQL join two tables and create new column

我在 HANA 上有两个由相同列构建的 table。 Table A 包含也在 table B 中的 ID,但它也包含不在 table B 中的 ID。Table B 也可能包含不在 [=] 中的 ID 38=] A.

我想加入两个 table。结果应列出 table A 或 table B 中的所有条目。但是,如果一个 ID 是两个 table 的一部分,则 ID 应该只有一个条目在结果中。

为了区分 ID 的用法,结果中应该有一个新列。它应该显示以下值之一:

这里是我想要实现的一些草图:

感谢您的帮助!

此致。

听起来你想要一个 full join:

select coalesce(a.id, b.id) as id,
       (case when a.id is null then 'B only'
             when b.id is null then 'A only'
             else 'Both'
        end) as which_table,
       . . .  -- whatever other columns you want
from a full join
     b
     on a.id = b.id;

做一个UNION ALL,然后GROUP BY其结果:

select id, description, max(ta), max(tb)
from
(
    select id, description, 'A' as ta, null as tb from tablea
    union all
    select id, description, null, 'B' from tableb
) dt
group by id, description

我已经为 Oracle 数据库完成了此操作。 也许它可以帮助...

select coalesce(a.id1, b.id2) as ID,
       coalesce(a.description1, b.description2) as Description
        , (case 
             when a.id1 = b.id2 then 'Table A+B'
             when b.id2 not in (select id1 from a) then 'Table B'
             else 'Table A'
        end) as Usage
from a full join b
on nvl(a.id1, b.id2) = b.id2;

此处演示:http://sqlfiddle.com/#!4/56232/1