获取最高值 sql

get the values mit highets value sql

给出以下 table(在 Oracle 中);

LVL KID     FATHER
1   POD001 DPR001
1   POD002 DPR002
1   POD003 POD002
2   POD003 DPR002
2   POD004 DPR001
1   POD004 POD001
2   POD005 POD002
1   POD005 POD003
3   POD005 DPR002

我要为所有孩子找爸爸。如果有多个父亲(POD003、POD004和POD005),从LVL列中取最大值。

结果一定是这样的;

   LVL   KID       FATHER
    1   POD001 DPR001
    1   POD002 DPR002
    2   POD003 DPR002
    2   POD004 DPR001
    3   POD005 DPR002

感谢您的帮助。

问候 塞尔达

您可以在 Oracle 中使用聚合:

select max(lvl) as lvl, kid,
       max(father) keep (dense_rank first order by lvl desc) as father
from t
group by kid;

keep 关键字用于(在本例中)实现聚合 "first value" 功能。在实践中,我发现它非常有效。

当然也可以和其他方法对比,比如:

select t.*
from t
where t.lvl = (select max(t2.lvl) from t t2 where t2.kid = t.kid);

您按孩子分组并获得最高等级并加入主table:

select t.*
from tablename t inner join (
  select kid, max(lvl) maxlvl 
  from tablename
  group by kid
) g
on g.kid = t.kid and g.maxlvl = t.lvl
order by t.kid

demo

或不存在:

select t.*
from tablename t
where not exists (
  select 1 from tablename
  where kid = t.kid and lvl > t.lvl
)
order by t.kid

demo

使用row_number()windows函数

with cte as
(
 select *,row_number()over(partition by kid order by lvl desc) rn
 from table_table
) select * from cte where cte.rn=1