SQL: Find the max record per group
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Retrieving the last record in each group
我有一个表,它有三个字段和数据。
1 2 3 4 5 6 7 | Name , Top , Total cat , 1 , 10 dog , 2 , 7 cat , 3 , 20 horse , 4 , 4 cat , 5 , 10 dog , 6 , 9 |
我想为每个
1 2 3 4 | Name , Top , Total cat , 3 , 20 horse , 4 , 4 Dog , 6 , 9 |
按名称顺序尝试了小组,但是按照结果给了小组的最高记录。 有人可以指导我吗?
1 2 3 4 5 6 | SELECT Name, Top, Total FROM sometable WHERE Total = (SELECT MAX(Total) FROM sometable i WHERE i.Name = sometable.Name) |
要么
1 2 3 4 5 6 7 8 9 | 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 |
你可以尝试类似的东西
1 2 3 4 5 6 7 8 9 | SELECT s.* FROM sometable s INNER JOIN ( SELECT Name, MAX(Total) MTotal FROM sometable GROUP BY Name ) sMax ON s.Name = sMax.Name AND s.Total = sMax.MTotal |
或者使用Exists子句,返回两个表中唯一存在的行
1 2 3 4 5 6 7 8 | SELECT * FROM sometable T WHERE EXISTS (SELECT 1 FROM (SELECT nombre, MAX(total) AS total FROM sometable TT GROUP BY nombre) TT WHERE T.name=TT.name AND T.total=TT.total ) |