【问题标题】:Oracle SQL - return record only if colB is the same for all of colAOracle SQL - 仅当 colB 对于所有 colA 都相同时才返回记录
【发布时间】:2015-12-12 04:29:48
【问题描述】:

我有一个如下表(表中当然还有其他数据):

Col A          Col B
1              Red
1              Red
2              Blue
2              Green
3              Black

我试图仅在所有 Col B 值都匹配时返回 Col A 的值,否则返回 null。

这将用作另一个将传递 Col A 值的 sql 语句的一部分,即 从 Col A = 1 的表中选择 *

我需要返回 Col B 中的值。上表中的正确结果应该是 Red,Black

有什么想法吗?

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    如果您只想要 A 中的 (而不是每一行),请使用 group by:

    select a
    from table t
    group by a
    having min(b) = max(b);
    

    注意:这会忽略 NULL 值。如果您想将它们视为附加值,则添加另一个条件:

    select a
    from table t
    group by a
    having min(b) = max(b) and count(*) = count(b);
    

    使用count(distinct) 也很诱人。但总的来说,count(distinct)min()max() 需要更多的处理工作。

    【讨论】:

    • 我实际上只想要 B 中的值。所以,在我上面的表格中,B 的有效值是:红色和黑色
    【解决方案2】:

    您可以使用case 语句。

    select cola,
    case when max(colb) = min(colb) and count(*) = count(colb) then max(colb)
    end as colb
    from tablename
    group by cola
    

    【讨论】:

      【解决方案3】:

      SQL Fiddle

      Oracle 11g R2 架构设置

      create table t( id number, color varchar2(20));
      
      insert into t values(1,'RED');
      insert into t values(1,'RED');
      insert into t values(2,'BLUE');
      insert into t values(2,'GREEN');
      insert into t values(3,'BLACK');
      

      查询 1

      select id
      from t
      group by id having min(color) = max(color)
      

      Results: |身份证 | |----| | 1 | | 3 |

      希望这就是你要找的东西.. :)

      【讨论】:

      • 几乎,除了我需要它返回红色,黑色,而不是 1,3
      • @flyingpie,请查看我的以下回答,如果这就是您所寻求的,请告诉我。
      【解决方案4】:

      这个怎么样?

      SQL Fiddle

      Oracle 11g R2 架构设置

      create table t( id number, color varchar2(20));
      
      insert into t values(1,'RED');
      insert into t values(1,'RED');
      insert into t values(2,'BLUE');
      insert into t values(2,'GREEN');
      insert into t values(3,'BLACK');
      

      查询 1

      select color from t where id in (
      select id
      from t
      group by id having min(color) = max(color) )
      group by color
      

      Results: |颜色 | |-------| |红色 | |黑色 |

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        相关资源
        最近更新 更多