检查组中列的所有值是否相同

时间:2014-10-15 07:41:00

标签: oracle

我在结果集中有以下一组值

Col1    Col2    Col3    Col4    Col5
M         CP    C        NO     T1
M         CP    C        NO     T2
M         CP    C        NO     T3
M         CP    A        YES    T4
M         CP    A        MAY    T5
M         CP    A        NO     T6
M         CP    D        WHY    T7
M         CP    E         NO    T8

查询)我想得到Col5的值,Col1,Col2和分组后的Col4 = NO的所有值都是 Col3。如何使用ORACLE中的单个查询来实现此目的。

例如:仅对组(M CP C获得值T1,T2,T3)和组(M CP E - 获得T8值)满足此条件

我的意思是在一个组中,所有行的Col4值都应为“NO”。

请建议。

3 个答案:

答案 0 :(得分:1)

如果我理解正确,此查询可能有所帮助:

SELECT Col1, Col2, Col3, Col4, Col5
  FROM(SELECT Col1, Col2, Col3, Col4, Col5,
              COUNT(*) OVER (PARTITION BY Col1, Col2, Col3) AS cnt1,
              COUNT(*) OVER (PARTITION BY Col1, Col2, Col3, Col4) AS cnt2 
         FROM your_table
      )
 WHERE Col4 = 'NO'
   AND cnt1 = cnt2;

答案 1 :(得分:0)

此查询选择具有Col4 = 'NO'的所有组:

select Col1, Col2, Col3
  from table1
 group by Col1, Col2, Col3     -- I want to group by Col1, Col2, Col3 that have
having min(Col4) = max(Col4)   -- a Col4 with same value
   and min(Col4) = 'NO';       -- and that value is NO

Col1    Col2    Col3
--------------------
M       CP      C
M       CP      E

请注意,使用min = max有助于确定列是否始终具有相同的值,在本例中为'NO'

现在,最后一个查询是从这两个组中选择所有Col5,再加上Col4='NO'

select Col5
  from table1
 where (col1, Col2, Col3) in (

    select Col1, Col2, Col3
      from table1
     group by Col1, Col2, Col3
     having min(Col4) = max(Col4)
        and min(Col4) = 'NO'
 );

输出您要查找的结果:

Col5
-------
T1
T2
T3
T8

答案 2 :(得分:0)

使用测试数据查询:

with data as(
select 'M'  as col1, 'CP' as col2, 'C'  as col3, 'NO' as col4, 'T1' as col5 from dual
 union all
select 'M',          'CP',         'C',          'NO',         'T2'         from dual
 union all
select 'M',          'CP',         'C',          'NO',         'T3'         from dual
 union all
select 'M',          'CP',         'A',          'YES',        'T4'         from dual
 union all
select 'M',          'CP',         'A',          'MAY',        'T5'         from dual
 union all
select 'M',          'CP',         'A',          'NO',         'T6'         from dual
 union all
select 'M',          'CP',         'D',          'WHY',        'T7'         from dual
 union all
select 'M',          'CP',         'E',          'NO',         'T8'         from dual)
select col1, col2, col3, max(col4), max(col5)  
  from data
  group by col1, col2, col3
  having max(col4) = min(col4)
     and max(col4) = 'NO';

输出:

COL1    COL2    COL3    MAX(COL4)   MAX(COL5)
M   CP  E   NO  T8
M   CP  C   NO  T3

请记住,我们假设cik5在组内只有col4 ='NO'的单一值。如果我们添加以下行,请考虑应该返回什么查询:

select 'M',          'CP',         'E',          'NO',         'T9'         from dual