显示具有匹配列值的记录

时间:2017-11-03 12:10:48

标签: sql oracle

我有一张包含以下结构的表格。

Name   Age 
----------
John   20    
Jack   20    
John   18
Steve  15
Jack   16
Lewis  17
Don    19
Jack   21
John   21
John   18

输出需要过滤,仅在Jack和John共享相同年龄时显示,类似于以下格式。我尝试了几种方法,但无法获得绝对结果。

Name   Age 
----------
John   20    
Jack   20    
Jack   21
John   21

8 个答案:

答案 0 :(得分:2)

尝试此查询。

SELECT a.name, a.age
FROM (SELECT name, age FROM a) a, (SELECT name, age FROM a) b
WHERE a.name <> b.name AND a.age = b.age;

答案 1 :(得分:0)

使用 SELF JOIN 并获取具有不同名称和相同年龄的行,其中只有John和Jack的名称。

<强>查询

select t1.name, t1.age
from your_tabel_name t1
join your_tabel_name t2
on t1.name <> t2.name
and t1.age = t2.age
where t1.name in ('Jack','John')
group by t1.name, t1.age
order by t1.age, t1.name;

Here 是一个sql小提琴演示。

答案 2 :(得分:0)

有一个只返回Jack和John行的cte。自我加入:

with cte as
(
    select name, age
    from tablename
    where name in ('Jack','John')
)
select t1.*
from cte t1
join cte t2 on t1.name <> t2.name and t1.age = t2.age

答案 3 :(得分:0)

试试这个:

    SELECT * 
        FROM YourTable WHERE AGE IN
        (
        SELECT Age 
        FROM YourTable 
        GROUP BY AGE 
        HAVING COUNT(1)=2
        )D
    ORDER BY AGE

答案 4 :(得分:0)

简单!试试这个最简单的

SELECT a.name, a.age FROM xx_ages a,xx_ages b WHERE a.name <> b.name AND a.age = b.age

答案 5 :(得分:0)

select distinct a.* 
from empp a  
join empp b 
on a.age=b.age 
and  a.name in ('Jack','John') 
and a.name!=b.name 
order by a.age

答案 6 :(得分:0)

http://htaccess.mwl.be/

使用self join并比较rowid

select
    t1.name, t1.age
from
    tblNames t1
    join tblNames t2 on
        t1.rowid <> t2.rowid and        
        t1.name <> t2.name and        
        t1.age = t2.age
where
    t1.name in ('Jack','John') 
order by t1.age, t1.name;

答案 7 :(得分:0)

你可以简单地使用它:

select t1.name, t1.age from table1 t1
join table1 t2 on t1.age=t2.age and t1.name <> t2.name;

这不仅限于Jack & John

SQL DEMO