2015-02-06 58 views
0

所以,我有一個表,是這樣的......獲得各組的最大價值在表

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); 

但是,這隻返回其中的所有頂級帳戶,而不是每個人。

回答

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

0

MYSQL,你可以試試這個方法也

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