Oracle PLSQL - 选择具有最大值的行
Oracle PLSQL - Selecting Row with Max Value
我有这样的行:
( a , #$@$ , $$ , 3 )
( c , ###$ , ## , 0 )
( a , #@$# , !! , 2 )
( b , #@## , $$ , 0 )
如果我想得到如下结果
( a , #$@$ , $$ , 3 )
( c , ###$ , ## , 0 )
( b , #@## , $$ , 0 )
这是基于按第 1 列分组并独立于其他列(2 和 3)选择第 4 列中具有最大值的行。
有没有办法不创建子查询?
为什么没有子查询?它们设计就是为了这个目的。
当前table内容:
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>
不使用子查询,您可以使用 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
;
我有这样的行:
( a , #$@$ , $$ , 3 )
( c , ###$ , ## , 0 )
( a , #@$# , !! , 2 )
( b , #@## , $$ , 0 )
如果我想得到如下结果
( a , #$@$ , $$ , 3 )
( c , ###$ , ## , 0 )
( b , #@## , $$ , 0 )
这是基于按第 1 列分组并独立于其他列(2 和 3)选择第 4 列中具有最大值的行。
有没有办法不创建子查询?
为什么没有子查询?它们设计就是为了这个目的。
当前table内容:
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>
不使用子查询,您可以使用 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
;