繁体   English   中英

使用group by和having子句获取多个最大行

[英]getting the multiple max row using group by and having clause

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);

但上面的查询给出了空集。 我做错了什么?

您可以使用另一个查询来获取最大值,然后使用HAVING子句匹配第一个查询的最大总和,因此如果有多个客户具有相同的最大数量,查询将返回所有客户

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM