如何排除具有相同值的组?

时间:2014-02-26 21:37:39

标签: oracle

我有一个场景,其中id绑定到多个值/代码,我想排除获取具有多个类型的所有id,其中一个应该是类型11但不是所有类型都应该是11。

create table t (t_id number, t_type number);

insert into t(T_ID, T_TYPE) values (1147, 1);
insert into t(T_ID, T_TYPE) values (1147, 35);
insert into t(T_ID, T_TYPE) values (1147, 11);
insert into t(T_ID, T_TYPE) values (1148, 11);
insert into t(T_ID, T_TYPE) values (1148, 11);
insert into t(T_ID, T_TYPE) values (1149, 1);
insert into t(T_ID, T_TYPE) values (1149, 11);
insert into t(T_ID, T_TYPE) values (1150, 35);
insert into t(T_ID, T_TYPE) values (1151, 11);
insert into t(T_ID, T_TYPE) values (1152, 27);
insert into t(T_ID, T_TYPE) values (1152, 11);
insert into t(t_id, t_type) values (1153, 1);
insert into t(t_id, t_type) values (1153, 27);

commit;

输出:

select * from t;

T_ID  T_TYPE
====  ======
1147       1
1147      35
1147      11
1148      11
1148      11
1149       1
1149      11
1150      35
1151      11
1152      27
1152      11
1153       1
1153      27

在这里,我想排除多次出现的t_id 1148,但始终与类型11绑定。

WITH ty AS(
   SELECT t_id
     FROM t
 GROUP BY t_id
   HAVING COUNT(1) > 1
)
SELECT t.t_id
  FROM t, ty
 WHERE ty.t_id = t.t_id
   AND t.t_type = 11
 GROUP 
    BY t.t_id;


      T_ID
----------
      1148
      1149
      1152
      1147

3 个答案:

答案 0 :(得分:1)

我认为这可以满足您的需求:

select t_id
from t
group by t_id
having sum(case when t_id = 11 then 1 else 0 end) > 0 and
       sum(case when t_id <> 11 then 1 else 0 end) > 0;

having子句确保它至少有一行 11且至少有一行不是 11。

答案 1 :(得分:0)

如果你计算t_type的明显出现次数,如下所示,它将排除t_id = 1148。

select t_id
  from t
 where t_id in(select t_id from t where t_type = 11)
 group 
    by t_id
having count(distinct t_type) > 1;

答案 2 :(得分:0)

select t_id from t where t_type = 11 
intersect 
select t_id from t where t_type <> 11