不要根据联合查询中的列选择重复项

时间:2015-11-05 16:14:29

标签: sql oracle

我有查询执行UNION

select deal_id, codptf from acc_deals where run_id = 1
union 
select deal_id, codptf from acc_deals where run_id = 2

然而,我发现自己有这个结果:

AAAA;1234
AAAA;3456
BBBB;4569

有一个重复的行,也就是第1行和第2行(相同的deal_id)。

如何排除其中一个重复的行?

2 个答案:

答案 0 :(得分:1)

看起来你需要全外连接

create table test(id varchar2(10), val int, run_id int);


insert into test values('AAAA', 1234, 1);
insert into test values('BBBB', 4569, 1);
insert into test values('AAAA', 3456, 2);
insert into test values('CCCC', 1111, 2);


select
  nvl(t1.id, t2.id) as id, nvl(t1.val, t2.val) as val
from 
(select * from test where run_id = 1) t1
full join
(select * from test where run_id = 2) t2
  on t1.id = t2.id

    ID  VAL
1   AAAA    1234
2   CCCC    1111
3   BBBB    4569

答案 1 :(得分:0)

作为@ are&#39的解决方案的替代方案,您可以改为执行以下操作:

perFormFetch

你会注意到那里有几列 - 我只是列出了一些选项,具体取决于你想要保留的值。您可以自行决定要使用哪些列,因为您没有指定在重复的情况下显示哪个值。

相关问题