0

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

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

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

4

2 回答 2

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' ;
于 2013-01-04T11:37:01.940 回答
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
于 2013-01-04T12:03:32.453 回答