我想得到user_id
以及总和金额最大的用户的金额总和。我不能使用LIMIT
,因为它只返回1条记录(多个用户的总和数量可能相同)
这是我的数据架构和一些记录
CREATE TABLE transactions (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
user_id BIGINT(20) NOT NULL,
amount FLOAT NOT NULL, PRIMARY KEY (id)
);
INSERT INTO transactions (user_id, amount) VALUES
(1, 1000),
(1, 1000),
(1, 1000),
(2, 2000),
(2, 1000),
(3, 1000);
以下是预期结果。
+---------+------+
| user_id | sum |
+---------+------+
| 1 | 3000 |
| 2 | 3000 |
+---------+------+
我可以使用以下sql获得上述结果。但是,我不知道有没有更好的方法。是否有必要重复两次相同的子查询?感谢。
SELECT T1.user_id, T1.sum
FROM (
SELECT user_id, SUM(amount) as sum
FROM transactions
GROUP BY user_id
) T1
WHERE T1.sum = (
SELECT MAX(T2.sum)
FROM (
SELECT user_id, SUM(amount) as sum
FROM transactions
GROUP BY user_id
) T2
)
GROUP BY T1.user_id;
答案 0 :(得分:2)
您可以将查询简化为
SELECT user_id, SUM(amount) as sum
FROM transactions
GROUP BY user_id
HAVING SUM(amount) = (
SELECT SUM(amount) as sum
FROM transactions
GROUP BY user_id
ORDER BY SUM(amount) DESC
LIMIT 1
)