【问题标题】:Oracle PLSQL - Selecting Row with Max ValueOracle PLSQL - 选择具有最大值的行
【发布时间】:2021-05-19 01:21:20
【问题描述】:

我有这样的行:

( a , #$@$ , $$ , 3 )
( c , ###$ , ## , 0 )
( a , #@$# , !! , 2 )
( b , #@## , $$ , 0 )

如果我想得到如下结果

( a , #$@$ , $$ , 3 )
( c , ###$ , ## , 0 )
( b , #@## , $$ , 0 )

这是基于第 1 列的分组,并选择第 4 列中具有最大值的行,独立于其他列(2 和 3)。

除了创建子查询之外,有没有办法做到这一点?

【问题讨论】:

    标签: sql oracle greatest-n-per-group


    【解决方案1】:

    不使用子查询,您可以使用 keep dense_rank 函数(其聚合版本),如下所示:

    with your_table (col1, col2, col3, col4) as (
    select 'a', '#$@$' , '$$' , 3 from dual union all
    select 'c', '###$' , '##' , 0 from dual union all
    select 'a', '#@$#' , '!!' , 2 from dual union all
    select 'b', '#@##' , '$$' , 0 from dual
    )
    select col1
    , max(col2)keep(dense_rank first order by col4 desc)col2
    , max(col3)keep(dense_rank first order by col4 desc)col3
    , max(col4)keep(dense_rank first order by col4 desc)col4
    from your_table t
    group by col1
    ;
    
    

    【讨论】:

      【解决方案2】:

      为什么没有子查询?它们设计就是为了这样的目的。

      当前表格内容:

      SQL> select * from test order by col1, col4;
      
      COL1  COL2  COL3        COL4
      ----- ----- ----- ----------
      a     #@$#  !!             2
      a     #$@$  $$             3
      b     #@$$  $$             0
      c     ###$  ##             0
      

      使用解析函数,按col1对行进行分区,并按col4降序排列;然后获取每个组(分区)的“第一”行。

      SQL> select col1, col2, col3, col4
        2  from (select col1, col2, col3, col4,
        3          row_number() over (partition by col1 order by col4 desc) rn
        4        from test
        5       )
        6  where rn = 1
        7  order by col1;
      
      COL1  COL2  COL3        COL4
      ----- ----- ----- ----------
      a     #$@$  $$             3
      b     #@$$  $$             0
      c     ###$  ##             0
      
      SQL>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-26
        • 2021-08-10
        • 2015-01-14
        • 2021-07-23
        • 2021-02-07
        • 1970-01-01
        • 1970-01-01
        • 2016-09-25
        相关资源
        最近更新 更多