使用union但只检索列的重复名称值

时间:2018-04-18 03:25:06

标签: sql oracle11g

表A

ID      Name        Age     Sex
====    ========    =====   =====
1       Jack        20      Male
2       James       18      Male
3       Jane        17      Female
4       Jessy       16      Female
5       John        34      Male

表B

ID      Name        Age     Sex
====    =========   =====   =====
1       Jack        21      Male
2       James       18      Male
3       Jane        17      Male
4       Jenna       17      Famale
5       John        34      Male        
6       John        34      Male    

我用

select ID, Name, Age, Sex
from Table A
union
select ID, Name, Age, Sex
from Table B

我得到以下结果

ID      Name        Age     Sex
====    =========   =====   =====
1       Jack        20      Male
1       Jack        21      Male
2       James       18      Male
3       Jane        17      Female
3       Jane        17      Male
4       Jessy       16      Female
4       Jenna       17      Famale
5       John        34      Male
6       John        34      Male

但我想要的是我希望我的预期结果只与名称重复。如果没有重复的名称,则不会在结果中显示

ID      Name        Age     Sex
====    =========   =====   =====
1       Jack        20      Male
1       Jack        21      Male
3       Jane        17      Female
3       Jane        17      Male
5       John        34      Male
6       John        34      Male

3 个答案:

答案 0 :(得分:0)

您可以使用子查询来获取显示多个的名称, 然后再次按名称加入表格。

你可以试试这个。

With T as (
    select ID, Name, Age, Sex from A       
    union 
    select ID, Name, Age, Sex from B
) 
SELECT t2.* FROM 
(
SELECT NAME,COUNT(1) FROM T
GROUP BY Name
HAVING COUNT(1) > 1
) t1 INNER JOIN T t2 ON t1.NAME = t2.Name

sqlfiddle:http://sqlfiddle.com/#!4/7c3fb/49

答案 1 :(得分:0)

为什么詹姆斯不是你期望的最终结果的一部分?

无论如何,这可能是你要找的东西:

yyyy

答案 2 :(得分:0)

首先执行union操作,然后再分组并选择重复的记录。

With abc as (
    select ID, Name, Age, Sex from Table A        union 
    select ID, Name, Age, Sex from Table B
) select * from abc where name in (select name from abc group by name having count(*) >1) ;

Sql Fiddle