基于值排除一组记录的Oracle SQL查询

基于值排除一组记录的Oracle SQL查询,sql,oracle,Sql,Oracle,我的文章标题可能有点尴尬,但让我试着解释一下我试图通过oracle sql查询实现什么 我的桌子如下 要求是,当seqNo由苹果共享时,我不希望选择该记录 仅当Apple单独拥有一个序列号而不被任何其他类别共享时,才选择该记录,如下表所示 非常感谢您的帮助 我试图基于seqNo进行分区,并在类别上对其进行排序,但由于类别是string,我无法实现它 |SeqNo | Category| |------ |---------| |1 | Banana| |3 | App

我的文章标题可能有点尴尬,但让我试着解释一下我试图通过oracle sql查询实现什么

我的桌子如下

要求是,当seqNo由苹果共享时,我不希望选择该记录

仅当Apple单独拥有一个序列号而不被任何其他类别共享时,才选择该记录,如下表所示

非常感谢您的帮助

我试图基于seqNo进行分区,并在类别上对其进行排序,但由于类别是string,我无法实现它

|SeqNo   |   Category|
|------ |---------|
|1    |   Banana|
|3    |   Apple ---> *do not select as sequence number is shared*|
|3    |   Orange ---> *do not select as sequence number is shared*|
|4    |   Mango|
|4    |   Banana|
|7    |   Orange---> *do not select as sequence number is shared*|
|7    |   Apple---> *do not select as sequence number is shared*|
|7    |   Mango---> *do not select as sequence number is shared*|
|9    |   Apple-->**Only Select this**|
|11   |   Banana|
|13   |   Mango|
|14   |   Apple-->**Only Select this**|
|18   |   Apple-->**Only Select this**|
|42   |   Mango|
模式:

 create table mytable (SeqNo int,   Category varchar(505));
 insert into mytable values(1    ,'Banana');
 insert into mytable values(3    ,'Apple');
 insert into mytable values(3    ,'Orange');
 insert into mytable values(4    ,'Mango');
 insert into mytable values(4    ,'Banana');
 insert into mytable values(7    ,'Orange');
 insert into mytable values(7    ,'Apple');
 insert into mytable values(7    ,'Mango');
 insert into mytable values(9    ,'Apple');
 insert into mytable values(11   ,'Banana');
 insert into mytable values(13   ,'Mango');
 insert into mytable values(14   ,'Apple');
 insert into mytable values(18   ,'Apple');
 insert into mytable values(42   ,'Mango');
查询1以查找具有单个记录且为“Apple”的seqno行

  with cte as ( select seqno,category,count(*)over(partition by seqno ) cnt from mytable )
  select * from cte where cnt=1 and trim(category)='Apple'
输出:

赛克诺 类别 碳纳米管 9 苹果 1. 14 苹果 1. 18 苹果 1.
我将使用窗口函数计算序号的苹果数和总行数,然后使用过滤逻辑:

select t.*
from (select t.*,
             count(*) over (partition by seq_no) as cnt,
             sum(case when category = 'Apple' then 1 else 0 end) over (partition by seq_no) as num_apple
      from t
     ) t
where num_apple = 0 or
      (num_apple = cnt and num_apple = 1);

最后一个条件是问题中模棱两可的条件。如果序号正好有两个苹果,我不知道该不该退。如果需要这种情况,请删除num_apple=1。

如果有两个苹果怎么办?是的,两个都需要选择。如果21->apple和21->apple是重复记录。因此,无论哪种方法都可以。如果任何答案有助于解决问题,请单击绿色复选框接受。JAK,非常感谢。我对你的问题进行了仔细的研究,得到了必要的答复。cte作为选择序号,类别,count*从mytable中选择*从mytable中选择*从cte中选择*,其中cnt=1,trimCategory='Apple'和mytable.seqno=cte.seqno;是的,再次感谢您的时间和帮助。@Asjadazez非常欢迎您。对不起,我误解了你的需要。但是,嘿,你做到了。。同源词。祝您好运。您可以简化您需要的最终查询。请检查我的问题1。太棒了,这对我来说也很有用,非常感谢您的时间和帮助。是的,只要您稍微询问一下,我就能得到我需要的。@Asjadazez。我不认为公认的答案适用于多个苹果。本查询涵盖了该情况。