如果组为空,则从查询中删除结果

时间:2020-01-24 23:37:15

标签: sql oracle group-by

我有下表:

条件:

如果所有grpid都有一个null客户身份,则不显示grpid的结果

grpid 145应该视为第二行上有custuserid

Custid    grpid   custuserid   date
  101       145                12/30/19
  101       145     dellf      1/1/20
  101       255     dellf      1/1/20
  201       456                1/1/20
  201       555     smithr     1/1/20

输出:

Custid    grpid   custuserid   date
  101       145                12/30/19
  101       145     dellf      1/1/20
  101       255     dellf      1/1/20
  201       555     smithr     1/1/20

筛选出这些结果的最佳方法?

我本以为可以使用first_value,但是有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

我会简单地使用exists

select t.*
from mytable t
where exists (
    select 1 from mytable t1 where t1.grpid = t.grpid and t1.custuserid is not null
)

相关子查询可确保至少一个具有相同grpid的记录具有非空的custuserid。为了提高性能,您需要在(grpid, custuserid)上建立索引。

您还可以使用窗口功能:

select *
from (
    select t.*, max(custuserid) over(partition by grpid) max_custuserid 
    from mytable t
) t
where max_custuserid is not null

或者,您可以加入汇总查询:

select t.*
from mytable t
inner join (
    select 
        grpid, 
        max(custuserid) 
    from mytable 
    group by grpid 
    having max(custuserid) is not null
) x on x.grpid = t.grpid

哪个选项效果最好取决于您的数据集(大小,基数等)。

答案 1 :(得分:1)

请尝试以下查询

select * from temp1 where grpid not in (select grpid from temp1 group by grpid having count(custorid)=0)
相关问题