日期:2014-05-17  浏览次数:20813 次

怎么写个sql,可以把2个表的2个字段中不同和重复的值挑出来?
比如表1的字段1中的记录如下:
aaa
bbb
ccc
ddd

表2的字段1中的记录如下:
aaa
bbb
ccc
ddd
ddd
eee

这个SQL既要把表2中多的eee挑出来,也要把重复的ddd也挑出来。
最后的结果是
ddd
eee

我用select * from x_tmp2 t where t.id not in (select t1.id from x_tmp1 t1)
和select * from x_tmp2 minus select * from x_tmp1都不行,只能挑出来eee,但是重复的ddd挑不出来。

------解决方案--------------------
SELECT c1 FROM tab2 WHERE not exisis(SELECT 1 FROM tab1 WHERE tab1.c1=tab2.c1)
   union
  SELECT c1 FROM tab2 GROUP BY c1 having count(*)>1;
------解决方案--------------------
select t.col2
from (select tb1.col as col1,tb2.col as col2,row_number()over(partition by tb2.col order by tb2.col)rn
from tb1,tb2
where tb1.col(+)=tb2.col)t
where t.col1 is null or (t.rn<>1);

------解决方案--------------------

create table T1(name VARCHAR2(50));
create table T2(name VARCHAR2(50));
insert into T2 (NAME) values ('aaa');
insert into T2 (NAME) values ('bbb');
insert into T2 (NAME) values ('ddd');
insert into T2 (NAME) values ('ddd');
insert into T2 (NAME) values ('eee');
insert into T2 (NAME) values ('eee');
insert into T2 (NAME) values ('aaa');
insert into T2 (NAME) values ('bbb');
insert into T2 (NAME) values ('ccc');
insert into T2 (NAME) values ('aaa');

insert into T1 (NAME)values ('aaa');
insert into T1 (NAME)values ('bbb');
insert into T1 (NAME)values ('ccc');
insert into T1 (NAME)values ('ddd');

commit;

select row_number() over(partition by name order by name) rn, t2.*
from t2
minus
select row_number() over(partition by name order by name) rn, t1.*
from t1;