表结构:

有如上数据,想要这样的结果:
按名字分组,取最大值
3 name1 809
4 name2 796
6 name3 888
方案1:
先按name分组,再查每个name的最大值,再查结果。
select t.* from KR_AA t where num = (select max(num) from KR_AA where name = t.name) order by t.name

方案2:
利用关键字exists找结果。
select a.* from KR_AA a where not exists(select 1 from KR_AA b where b.name = a.name and b.num > a.num)

方案3:
利用row_number() over()排序,然后取第一条数据。
select * from (select A.*,row_number() over(partition by name order by num desc) aa from KR_AA A) b where b.aa = 1

本文探讨了三种使用SQL从数据库中按名字分组并选取每组最大值的方法。方案包括:直接查询最大值、使用exists关键字及row_number()窗口函数。适用于数据库管理员和SQL开发者。
20万+

被折叠的 条评论
为什么被折叠?



