【问题标题】:Return records from select based on column value. Oracle根据列值从选择返回记录。甲骨文
【发布时间】:2020-06-09 06:10:34
【问题描述】:

所以我确实选择了这样的女巫:

SELECT * FROM database1 WHERE ID = 3933185

女巫选择返回给我的记录是:

ID          VALUE   ATTR_VALUE
3,933,185   1           1
3,933,185   1           1
3,933,185   1           1
3,933,185   1           2
3,933,185   1           2

正如您所见,每个 attr_value 列可能有不同的值,12,仅此而已。

那么我应该添加什么来进行检查,当attr_value 存在且值为1 时,它将返回attr_value = 1 的记录,否则它将返回attr_value = 2 的位置。

希望我的问题很清楚。

【问题讨论】:

    标签: sql oracle select greatest-n-per-group window-functions


    【解决方案1】:

    我想你想要:

    select t.*
    from t
    where t.value = (select min(t2.value) from t t2 where t2.id = t.id);
    

    您还可以使用分析函数:

    select t.*
    from (select t.*, min(t.value) over (partition by id) as min_value
          from t
         ) t
    where value = min_value;
    

    【讨论】:

      【解决方案2】:

      你可以在这里使用存在逻辑:

      SELECT d1.*
      FROM database1 d1
      WHERE NOT EXISTS (SELECT 1 FROM database1 d2
                        WHERE d1.ID = d2.ID AND d2.ATTR_VALUE > d1.ATTR_VALUE);
      

      【讨论】:

        【解决方案3】:

        如果我没看错,你可以使用解析函数:

        select id, value, attr_value
        from (select t.*, rank() over(order by attr_value) rn from mytable t) t
        where rn = 1
        

        【讨论】:

          猜你喜欢
          • 2020-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多