【问题标题】:Select different values from table based on condition根据条件从表中选择不同的值
【发布时间】:2016-02-25 15:41:47
【问题描述】:

表结构如下:

++ID++++READ_ID++++READ_TYPE
  101    201          30
  102    201          35
  103    201          40
  104    201          60
  105    202          50
  106    202          60

我需要根据以下条件选择READ_TYPE:

条件 1:检查每个 READ_ID 是否存在 30,35 或 40。如果存在,则选择 30、35 和 40 中存在的最大 READ_TYPE。 例如 READ_ID 201 有 30,35,40 和 60。结果必须是 40。

条件 2:如果不存在 30、35 或 40,则获取 read_type 的最大值。 例如 READ_ID 202 有 50 和 60。结果必须是 60。

如何通过单个 oracle SQL 查询实现这一点。

【问题讨论】:

    标签: sql oracle plsql oracle-sqldeveloper


    【解决方案1】:

    您可以使用条件聚合来做到这一点:

    select read_id,
           (case when sum(case when read_type in (30, 35, 40) then 1 else 0 end) > 0
                 then max(case when read_type in (30, 35, 40) then read_type end) 
                 else max(read_type)
            end) as themax
    from t
    group by read_id;
    

    【讨论】:

      【解决方案2】:

      你可以使用KEEP子句来得到你想要的:

      select read_id
           , max(read_type) keep (dense_rank last
                                    order by case when read_type not in (30,35,40)
                                                  then 1
                                                  else 2
                                             end
                                           , read_type) max_read_type
        from Your_Table
        group by read_id;
      

      【讨论】:

        【解决方案3】:

        请试试这个查询。我在一个示例上对其进行了测试,它在 oracle 上运行良好。

        select READ_ID, MAX(READ_TYPE) from tab
        where READ_TYPE in (30,35,40)
        group by READ_ID
        union
        select READ_ID, MAX(READ_TYPE) from tab t1
        where not exists 
        (select 1 from tab t2 where t2.READ_TYPE in (30,35,40) and t1.READ_ID = t2.READ_ID)
        group by READ_ID
        

        【讨论】:

          猜你喜欢
          • 2014-11-26
          • 1970-01-01
          • 2016-06-13
          • 1970-01-01
          • 1970-01-01
          • 2022-11-02
          • 2022-01-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多