Mysql 使用GROUPBY和having子句获取多个max行
问题: 从上表中,我想获得最大数量的客户id和数量 输出应该如下所示Mysql 使用GROUPBY和having子句获取多个max行,mysql,sql,Mysql,Sql,问题: 从上表中,我想获得最大数量的客户id和数量 输出应该如下所示 mysql> select * from raj; +------+----------+ | id | quantity | +------+----------+ | 1 | 250 | | 1 | 250 | | 2 | 250 | | 2 | 150 | | 3 | 150 | | 3 | 150 | | 4
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);
我尝试过的:
+------+---------------+
| id | sum(quantity) |
+------+---------------+
| 1 | 500 |
|
| 4 | 500 |
+------+---------------+
但上面的查询给出的是空集。
我做错了什么?您可以这样做b使用另一个查询来获得最大的总和,然后使用
HAVING
子句来匹配第一个查询的最大总和,因此如果有多个客户具有相同的最大数量,则查询将返回所有客户
select id,sum(quantity) quant
from raj
group by(id)
having max(quant);
问题是@zerkms编辑了我的问题。我想使用group by和havingso获取最大数量行。可以你的问题是什么?
ORDER BY
+LIMIT 1
@zerkms我已经清楚地提到了这个问题。。
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
select groups.*
from
(select id,sum(quantity) quant
from raj
group by(id)) groups JOIN
(select max(quant) as max_q
from (select id,sum(quantity) quant
from raj
group by(id)) tmp
) max_data ON groups.quant=max_data.max_q