获取表中每个组的最大值

时间:2015-02-06 17:09:45

标签: mysql sql

所以,我有一张类似这样的表......

 person    |   account    |   accountbalance
--------------------------------------------
  1               a             100
  1               b             250
  1               c             283
  2               a             25
  2               b             199
  3               a             65

对于每个人,我需要找到余额最高的帐户。我现在正在这样做:

SELECT person, account, accountbalance FROM mytable
AND accountbalance=  
    (SELECT MAX(accountbalance) FROM mytable);

但这只会让所有人中的ONE账户全部退回,而不是每个人。

2 个答案:

答案 0 :(得分:2)

一种方法是计算派生表中的最大值并加入:

SELECT mytable.person, account, accountbalance 
FROM mytable
JOIN (
  SELECT person, MAX(accountbalance) MaxAccountBalance 
  FROM mytable
  GROUP BY person
) t ON mytable.person = t.person
   AND mytable.accountbalance = t.MaxAccountBalance;

或者你可以在where子句中做一个相关的子查询(这就是你几乎所做的 - 你只是错过了必要的相关性):

SELECT person, account, accountbalance 
FROM mytable m1
WHERE accountbalance = (SELECT MAX(accountbalance) FROM mytable WHERE person = m1.person);

Sample SQL Fiddle

答案 1 :(得分:0)

对于MYSQL,您也可以尝试这种方式

select * 
from (select * from mytable order by `person`, accountbalance desc, account) x
group by `person`