oracle 我想找出2个表之间的差异,输出应该是预期的格式

yiytaume  于 2023-06-22  发布在  Oracle
关注(0)|答案(2)|浏览(112)

我想找出2个表之间的差异,输出应该是预期的格式
表AAA(NUM,TXT)
表BBB(NUM,TXT)
我在oracle中使用下面的查询来获得差异

select 'only A' where_, only_a.* from (select num, txt from AAA minus select num, txt from BBB) only_a union all
select 'only B' where_, only_b.* from (select num, txt from BBB minus select num, txt from AAA) only_b

输出为

我想要或期望的输出是

我想最好的查询,以获得所需的格式输出,如在这个问题所示

rfbsl7qr

rfbsl7qr1#

你可以用一个FULL OUTER JOIN(而不是你的查询,SELECT从表中s 4次,使用2个MINUS es和一个UNION ALL):

SELECT CASE
       WHEN a.num IS NOT NULL
       THEN 'only A'
       ELSE 'only B'
       END AS what,
       COALESCE(a.num, b.num) AS num,
       CASE
       WHEN a.num IS NOT NULL
       THEN a.txt
       ELSE b.txt
       END AS txt
FROM   aaa a
       FULL OUTER JOIN bbb b 
       ON a.num = b.num AND a.txt = b.txt
WHERE  a.num IS NULL
OR     b.num IS NULL
ORDER BY num, what

其中,对于样本数据:

CREATE TABLE AAA(NUM,TXT) AS
SELECT 1,   'One'   FROM DUAL UNION ALL
SELECT 2,   'too'   FROM DUAL UNION ALL
SELECT 3,   'Three' FROM DUAL UNION ALL
SELECT 4,   'Four'  FROM DUAL;

CREATE TABLE BBB(NUM,TXT) AS
SELECT 1,   'One'  FROM DUAL UNION ALL
SELECT 3,   NULL   FROM DUAL UNION ALL
SELECT 4,   'Four' FROM DUAL UNION ALL
SELECT 2,   'Two'  FROM DUAL UNION ALL
SELECT 5,   'Five' FROM DUAL;

输出:
| 什么|NUM| TXT|
| - -----|- -----|- -----|
| 只有A| 2|太|
| 只有B| 2|两个|
| 只有A| 3|三个|
| 只有B| 3|联系我们|
| 只有B| 5个|五|
fiddle

b5lpy0ml

b5lpy0ml2#

样本数据:

SQL> with
  2  aaa (num, txt) as
  3    (select 1, 'One'   from dual union all
  4     select 2, 'too'   from dual union all
  5     select 3, 'Three' from dual union all
  6     select 4, 'Four'  from dual
  7    ),
  8  bbb (num, txt) as
  9    (select 1, 'One'  from dual union all
 10     select 2, 'Two'  from dual union all
 11     select 3, null   from dual union all
 12     select 4, 'Four' from dual union all
 13     select 5, 'Five' from dual
 14    )

查询:

15  select 'only A' what, a.* from aaa a minus select 'only A', b.* from bbb b
 16  union all
 17  select 'only B' what, b.* from bbb b minus select 'only B', a.* from aaa a
 18  order by 2, 1;

WHAT          NUM TXT
------ ---------- -----
only A          2 too
only B          2 Two
only A          3 Three
only B          3
only B          5 Five

SQL>

相关问题