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

时间:2014-04-10 05:02:23

标签: mysql sql

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用其他查询来获取最大值,然后使用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

答案 1 :(得分:1)

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