假设我有一个“订单”表,我必须打印花费超过100美元的客户列表。为此,我使用了HAVING和GROUP BY:
SELECT clientID, SUM(amount) AS spent
FROM orders
GROUP BY clientID
HAVING spent >= 100;
现在我想知道在SAME查询中是否可以获得花费超过100美元的所有客户以及客户/行总数所花费的总金额。
答案 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;