通过HAVING和GROUP BY获得总金额

时间:2016-05-24 13:35:16

标签: mysql group-by sum having

假设我有一个“订单”表,我必须打印花费超过100美元的客户列表。为此,我使用了HAVING和GROUP BY:

SELECT clientID, SUM(amount) AS spent
FROM orders
GROUP BY clientID
HAVING spent >= 100;

现在我想知道在SAME查询中是否可以获得花费超过100美元的所有客户以及客户/行总数所花费的总金额。

  • john> $ 125
  • doe> $ 100
  • TOTAL> 225 $(2客户)

2 个答案:

答案 0 :(得分:2)

WITH ROLLUP是你的朋友。

SELECT clientID, SUM(amount) AS spent
FROM orders
GROUP BY clientID
WITH ROLLUP
HAVING spent >= 100;

答案 1 :(得分:1)

ANSI SQL-92标准方法:

SELECT clientID, SUM(amount) AS spent
FROM orders
GROUP BY clientID
HAVING SUM(amount) >= 100;

WITH ROLLUP方法会产生一行,其中包含null clientID和所有clientID中的sum(amount)

MySQL也支持:

SELECT clientID, SUM(amount) AS spent
FROM orders
GROUP BY clientID
HAVING spent >= 100;

回答实际问的问题:

SELECT clientID, SUM(spent) as spent
FROM (
  SELECT clientID, SUM(amount) AS spent
  FROM orders
  GROUP BY clientID
  HAVING spent >= 100
)
GROUP BY clientID
WITH ROLLUP;