Oracle / SQL - 查找具有一个值的记录,不包括类似记录

时间:2011-03-02 15:46:14

标签: sql oracle

好的,让我做一个更好的解释。假设我有一个person列和一个类型列。同一个人可以在表中多次,但具有不同的类型。我想要所有具有指定类型的人,除非他们与其他类型一起列出。

所以给出了这个数据

Person  Type
--------------
Bob     S
Sue     S
Bob     O
Tom     S
Frank   S
Frank   R

我想看看有类型S的人,但是也没有列出类型O或者R.所以我的查询应该返回

Person  Type
--------------
Sue     S
Tom     S

谢谢!

7 个答案:

答案 0 :(得分:2)

这样做:

SELECT person
FROM table
GROUP BY person
HAVING MIN(type) = 'S' AND MAX(type) = 'S'

但是,如果你有同一个人的多个记录并输入'S',那么这将删除那些重复

答案 1 :(得分:0)

select person, type
    from myTable
    where type = 'S'
        and person NOT IN (
            select person
                from myTable
                where type in ('O', 'R')
        )

答案 2 :(得分:0)

也许是这样的:

select distinct Person, Type
from table
where (Person, type) in
  (select distinct Person, Type
   from table
   having count(*) = 1)  

添加了区别来处理您的案件。

答案 3 :(得分:0)

作为NOT IN语法的一个选项,外连接也可以处理

select t1.person, t1.type    
from   person_Type t1, person_type t2
where  t1.person = t2.person(+)
and    t1.type != t2.type(+)
and    t1.type = 'S'
and    t2.type is null;

或者,在回应评论时 - 对于那些喜欢ANSI语法的人......

select t1.person, t1.type
from  person_type t1
left outer join person_type t2
on  t2.person = t1.person
and t2.type != t1.type
where t1.type = 'S'
and t2.type is null;

答案 4 :(得分:0)

SELECT DISTINCT person, ptype FROM persons p1 
WHERE (SELECT COUNT( DISTINCT ptype ) 
FROM persons p2 
WHERE p2.person = p1.person) = 1;

答案 5 :(得分:0)

这个怎么样:

SELECT  person, type 
FROM      MyTable   t1 
WHERE (
        SELECT COUNT( DISTINCT  type ) 
        FROM @MyTable t2 
        WHERE t2.person = t1.person 
        AND  t1.Type='s'
        ) = 1
GROUP BY person, type 

答案 6 :(得分:0)

出于性能原因,我喜欢Gary的选择,但更简单的方法是:

SELECT Person FROM mytable WHERE Type = 'S'
MINUS
SELECT Person FROM mytable WHERE Type IN ('O','R');