列A具有3个相同的值,需要检查同一列A的列B值

时间:2013-01-04 11:31:10

标签: oracle

例如,我将列A部门和列B作为员工类型,我需要检查以下内容。

Department    Emp Type  
Dep1            S  
Dep1            H  
Dep1            P  
Dep2            H  
Dep2            H  
Dep2            H  

我需要检索所有3行的H员工类型的部门。如果emp类型不同,我需要忽略该部门。

2 个答案:

答案 0 :(得分:3)

SELECT DISTINCT Department
FROM tableX  t
WHERE NOT EXISTS
      ( SELECT *
        FROM tableX  s
        WHERE s.Department = t.Department
          AND s.EmpType <> 'H'
      ) ;

如果您有(Department, EmpType)的索引,最快的方式可能是:

SELECT Department
FROM tableX  t
GROUP BY Department
HAVING MIN(EmpType) = 'H'
   AND MAX(EmpType) = 'H' ;

答案 1 :(得分:3)

你可以使用一个组来过滤掉那些只有H:

的组
SQL> create table dept(dep varchar2(5), typ varchar2(1));

Table created.

SQL> insert into dept
  2  select 'Dep1', 'S' from dual union all
  3  select 'Dep1', 'H' from dual union all
  4  select 'Dep1', 'P' from dual union all
  5  select 'Dep2', 'H' from dual union all
  6  select 'Dep2', 'H' from dual union all
  7  select 'Dep2', 'H' from dual;

6 rows created.

SQL> select dep
  2    from dept
  3   group by dep
  4   having count(distinct typ) = 1
  5      and max(typ) = 'H';

DEP
-----
Dep2