Oracle SQL -- 合并两个表,但从一个表中提取重复项?

2021-09-14 00:00:00 sql union oracle

我有这些表:

Table A
Num Letter 
1   A      
2   B      
3   C     

Table B
Num Letter
2   C      
3   D   
4   E 

我想联合这两个表,但我只希望每个数字出现一次.如果两个表中出现相同的数字,我希望它来自表 B 而不是表 A.

I want to union these two tables, but I only want each number to appear once. If the same number appears in both tables, I want it from Table B instead of table A.

Result
Num Letter
1   A
2   C
3   D
4   E

我怎么能做到这一点?联合将保留重复项,而相交将仅捕获相同的行——当它具有相同的数字时,我认为一行是重复的,而不管字母如何.

How could I accomplish this? A union will keep duplicates and an intersect would only catch the same rows -- I consider a row a duplicate when it has the same number, regardless of the letter.

推荐答案

还有一个:

SELECT COALESCE(b.num, a.num) num, COALESCE(b.letter, a.letter) letter
  FROM a FULL JOIN b ON a.num = b.num
 ORDER BY 1;

使用您的数据:

WITH a AS 
(SELECT 1 num, 'A' letter FROM dual
 UNION ALL SELECT 2, 'B' FROM dual
 UNION ALL SELECT 3, 'C' FROM dual),
b AS
(SELECT 2 num, 'C' letter FROM dual
 UNION ALL SELECT 3, 'D' FROM dual
 UNION ALL SELECT 4, 'E' FROM dual)
SELECT COALESCE(b.num, a.num) num, COALESCE(b.letter, a.letter) letter
  FROM a FULL JOIN b ON a.num = b.num
 ORDER BY 1;

       NUM L
---------- -
         1 A
         2 C
         3 D
         4 E

相关文章