Oracle SQL比较聚合行

时间:2018-06-13 10:02:32

标签: sql oracle

陷入相对简单的SQL ......

有人可以提出一些代码来检索aValue不同的聚合行(GroupID分组)的GroupID吗? 例如,在下表中,我需要获得GroupID' 4'因为同一组中的2个项目(4)具有不同的aValue

GroupId ItemID  aValue
4       19      Hello 
4       20      Hello1
5       78      Hello5
5       86      Hello5

2 个答案:

答案 0 :(得分:1)

您可以使用having子句查看不同值的计数:

-- CTE for your sample data
with your_table (groupid, itemid, avalue) as (
  select 4, 19, 'Hello' from dual
  union all select 4, 20, 'Hello1' from dual
  union all select 5, 78, 'Hello5' from dual
  union all select 5, 86, 'Hello5' from dual
)
select groupid
from your_table
group by groupid
having count(distinct avalue) > 1;

   GROUPID
----------
         4

如果您实际上还想查看单个值,则可以在子查询中使用分析计数,并使用where而不是having对其进行过滤:

-- CTE for your sample data
with your_table (groupid, itemid, avalue) as (
  select 4, 19, 'Hello' from dual
  union all select 4, 20, 'Hello1' from dual
  union all select 5, 78, 'Hello5' from dual
  union all select 5, 86, 'Hello5' from dual
)
select groupid, itemid, avalue
from (
  select groupid, itemid, avalue,
    count(distinct avalue) over (partition by groupid) as value_count
  from your_table
)
where value_count > 1;

   GROUPID     ITEMID AVALUE
---------- ---------- ------
         4         19 Hello 
         4         20 Hello1

答案 1 :(得分:0)

我会这样做:

select GroupId
from table t
group by GroupId
having min(aValue) <> max(aValue);

但是,如果您想要所有columns/expression,那么您可以使用EXISTS

select t.*
from table t
where exists (select 1  
              from table t1 
              where t1.GroupId = t.GroupId and 
                    t1.avalue <> t.avalue
             );