获取值mit最高值sql

问题描述 投票:0回答:3

给出下表(在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

谢谢您的帮助。

关心Serdar

sql oracle function window max
3个回答
1
投票

您可以在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关键字(在本例中)来实现聚合“第一个值”功能。在实践中,我发现它非常有效。

当然,您可以将其与其他方法进行比较,例如:

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

0
投票

使用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

0
投票

您按小孩分组并获得最高级别并加入主表:

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

或使用NOT EXISTS:

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

© www.soinside.com 2019 - 2024. All rights reserved.