美文网首页MySql
SQL获取分组后取某字段最大一条记录(求每个类别中最大的值的列表

SQL获取分组后取某字段最大一条记录(求每个类别中最大的值的列表

作者: 让你变好的过程从来都不会很舒服 | 来源:发表于2021-11-22 09:22 被阅读0次

方法一(效率最高):

select * from test as a 
where typeIndex = (select max(b.typeIndex) from test b where a.type = b.type );

方法二(效率次之):

select a.* from test a,
(select type,max(typeindex) typeindex from test group by type) b
where a.type=b.type and a.typeindex = b.typeindex order by a.type

方法三(效率最低):

select * from 
(
select *,ROW_NUMBER() OVER(PARTITION BY type ORDER BY typeindex DESC) AS num
from test
)t where t.num=1

相关文章

网友评论

    本文标题:SQL获取分组后取某字段最大一条记录(求每个类别中最大的值的列表

    本文链接:https://www.haomeiwen.com/subject/ablawltx.html