SQL:查找每个组的最大记录 [英] SQL: Find the max record per group
本文介绍了SQL:查找每个组的最大记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
检索每个组中的最后一条记录
Possible Duplicate:
Retrieving the last record in each group
我只有一个表,其中有三个字段和数据.
I have one table, which has three fields and data.
Name , Top , Total
cat , 1 , 10
dog , 2 , 7
cat , 3 , 20
horse , 4 , 4
cat , 5 , 10
dog , 6 , 9
我想为每个Name
选择具有最高Total
值的记录,所以我的结果应该是这样的:
I want to select the record which has highest value of Total
for each Name
, so my result should be like this:
Name , Top , Total
cat , 3 , 20
horse , 4 , 4
Dog , 6 , 9
我尝试了按总数进行按名称分组,但它给出了按结果分组的最高记录.有人可以引导我吗?
I tried group by name order by total, but it give top most record of group by result. Can anyone guide me, please?
推荐答案
select
Name, Top, Total
from
sometable
where
Total = (select max(Total) from sometable i where i.Name = sometable.Name)
或
select
Name, Top, Total
from
sometable
inner join (
select max(Total) Total, Name
from sometable
group by Name
) as max on max.Name = sometable.Name and max.Total = sometable.Total
这篇关于SQL:查找每个组的最大记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文