MySQL组与MAX没有按预期工作?

时间:2013-06-01 12:09:37

标签: mysql sql

我有一张桌子:

ID | User | Amount
1  | 1    | 50
2  | 1    | 80
3  | 2    | 80
4  | 2    | 100
5  | 1    | 90
6  | 1    | 120
7  | 2    | 120
8  | 1    | 150
9  | 2    | 300

我查询:

SELECT * FROM TABLE ORDER BY amount DESC group by userid

我得到了这个:

ID | User | Amount
1  | 1    | 50
2  | 1    | 80

但我在期待:

ID | User | Amount
9  | 2    | 300
8  | 1    | 150

我的sql出了什么问题?

2 个答案:

答案 0 :(得分:5)

分组时,您必须对所有未按

分组的列使用max()等聚合函数
select t.* 
from table t
inner join 
(
   SELECT userid, max(amount) as total
   FROM TABLE 
   group by userid
) x on x.userid = t.userid and x.total = t.amount
ORDER BY t.amount DESC 

答案 1 :(得分:0)

另一种解决方案。检查SQL Fiddle 使用FIND_IN_SET子句

SELECT
  ua.*
FROM user_amount ua
WHERE FIND_IN_SET(ua.amount,(SELECT
                               MAX(ua1.amount)
                             FROM user_amount ua1
                             WHERE ua1.user = ua.user)) > 0
ORDER BY amount desc;  

使用IN子句

SELECT
  ua.*
FROM user_amount ua
WHERE ua.amount IN (SELECT
                               MAX(ua1.amount)
                             FROM user_amount ua1
                             WHERE ua1.user = ua.user)
ORDER BY amount desc