0

我有一张桌子:

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有什么问题?

4

2 回答 2

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 
于 2013-06-01T12:11:34.427 回答
0

另一种解决方案。检查 SQL Fiddle UsingFIND_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
于 2013-06-01T13:00:44.853 回答