Oracle SQL:尝试根据列值的组合排除行

时间:2014-02-11 17:03:05

标签: sql oracle oracle-sqldeveloper oracle11gr2

我有一个表格,其中包含我需要排除行的ID列表。对于每一行,ID可以在comment_code列中具有一个值。我需要从结果中排除具有两个特定值组合的ID,并保留只包含这两个值之一的ID。对不起,如果不清楚的话。

表示例:

ID     SEQUENCE     FUNCTION     COMMENT_CODE
---------------------------------------------------------------
1        1             tree          apple
1        2             bush          orange
2        1             tree          apple
2        2             tree          banana
3        1             bush          strawberry

需要输出:

ID     SEQUENCE     FUNCTION     COMMENT_CODE
---------------------------------------------------------------
2        1             tree          apple

基本上,如果ID的行有'apple'作为comment_code,行有'orange'作为注释代码,我不希望在结果中看到该ID。如果一个ID有一行带有'apple'作为评论代码,我想在我的结果中看到它们,不管他们可能有什么其他评论代码,只要他们没有橙色评论代码。

非常感谢任何帮助。我尝试过使用exists和not exists子句以及listagg的组合将每个ID的comment_code值组合在一起,但是我没有得到预期的结果。

3 个答案:

答案 0 :(得分:2)

此方法使用聚合来查找具有这两个值的所有id。这用作使用left outer join的排除列表:

select *
from table t left outer join
     (select id
      from table t
      group by t.id
      having sum(case when comment = 'apple' then 1 else 0 end) > 0 and
             sum(case when comment = 'orange' then 1 else 0 end) > 0
     ) toexclude
     on t.id = toexclude.id
where toexclude.id is null;

答案 1 :(得分:0)

这样的事情应该有效。

select *
from yourtable
where sequence = 1
and whatever

答案 2 :(得分:0)

选择*
  来自表t
 存在的地方(从双重中选择1)                 其中t.function ='tree'                   和t.comment_code ='apple')