根据条件过滤数据

时间:2018-04-27 14:57:11

标签: sql oracle not-exists

我有一张如下表格。我需要找出排名为R1但从未排名为C1和C2的雇员。

Id  ECode Name Rank
1   EMP1    AA  R1
2   EMP2    BB  R1
3   EMP1    AA  R2
4   EMP1    AA  C1
5   EMP1    AA  C2
6   EMP1    AA  C3
7   EMP2    BB  C4
8   EMP2    BB  C5
9   EMP3    CC  R1
10  EMP3    CC  C1
11  EMP3    CC  C2
12  EMP3    CC  C4
13  EMP4    DD  R1
14  EMP4    DD  C3

6 个答案:

答案 0 :(得分:1)

试试这个:

SELECT *
  FROM EMPLOYES  A
 WHERE RANK = 'R1'
   AND NOT EXISTS(SELECT 1 
                    FROM EMPLOYES  B
                   WHERE B.ECODE = A.ECODE
                     AND RANK IN ('C1','C2')
                     AND ROWNUM = 1)

答案 1 :(得分:1)

一种方法使用员工聚合:

SELECT ECode, Name
FROM yourTable
GROUP BY ECode, Name
HAVING
    SUM(CASE WHEN Rank = 'R1' THEN 1 ELSE 0 END) > 0 AND
    SUM(CASE WHEN Rank IN ('C1', 'C2') THEN 1 ELSE 0 END) = 0

答案 2 :(得分:1)

我愿意:

SELECT ecode, name
FROM t
WHERE rank IN ('R1', 'C1', 'C2')
GROUP BY ecode, name
HAVING MIN(rank) = MAX(rank) AND MAX(rank) = 'R1';

答案 3 :(得分:0)

您可以结合使用existsnot exists

select * 
from table t 
where exists (select 1 from table where ECode = t.ECode and Rank = 'R1') AND 
      not exists (select 1 from table where ECode = t.ECode and Rank IN ('C1', 'C2'))

答案 4 :(得分:0)

显然使用NOT EXISTS

select *
  from mytable t
 where t.rank = 'R1' 
   and not exists ( select ECode from mytable where ECode = t.ecode and  rank in ('C1','C2') );

答案 5 :(得分:-2)

Select * from (tablename)
where Rank = 'R1'
and Rank not in (Select Rank from (tablename)
where Rank = 'C1' 
or Rank = 'C2')