mysql> select * from raj;
+------+----------+
| id | quantity |
+------+----------+
| 1 | 250 |
| 1 | 250 |
| 2 | 250 |
| 2 | 150 |
| 3 | 150 |
| 3 | 150 |
| 4 | 150 |
| 4 | 350 |
+------+----------+
8 rows in set (0.00 sec)
mysql> select id,sum(quantity)
-> from raj
-> group by(id);
问题: 从上表中我想获得最大数量的 customer_id 和 quant 输出应该是这样的
+------+---------------+
| id | sum(quantity) |
+------+---------------+
| 1 | 500 |
|
| 4 | 500 |
+------+---------------+
我尝试过的:
select id,sum(quantity) quant
from raj
group by(id)
having max(quant);
但是上面的查询给出的是空集。 我做错了什么?
最佳答案
你可以这样做 b 使用另一个查询来获取总和的最大值,然后使用 HAVING
子句来匹配你的第一个查询的最大总和,这样查询将返回所有客户如果有超过 1 个客户具有相同的最大数量
SELECT id,
SUM(quantity) quant,t.max_sum
from Table1
JOIN (SELECT SUM(quantity) max_sum
FROM Table1
GROUP BY id
ORDER BY max_sum DESC LIMIT 1) t
GROUP BY id
HAVING quant = t.max_sum
Fiddle Demo
关于mysql - 使用 group by 和 having 子句获取多个最大行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22979022/