Mysql显示名称,SUM(金额)WHERE金额小于210且SUM(金额)大于或等于210

时间:2013-07-29 06:57:44

标签: mysql

Mysql表

Name   | Amount
------------
name1  | 150
name1  | 90
name2  | 100
name2  | 110
name3  | 10

结果需要像

这样的东西
Name   | SUM(Amount)
------------
name1  | 240
name2  | 210

尝试

 SELECT Name, SUM(Amount)
 WHERE Amount < 210 AND SUM(Amount) >= 210
 GROUP BY Name

但是得到错误SQLSTATE[HY000]: General error: 1111 Invalid use of group function

如果我移除AND SUM(Amount) >= 210代码

试图思考......我是否需要首先获得SUM(Amount) AS SumAmount并在同一个查询中而不是AND SUM(Amount) >= 210使用AND SumAmount >= 210? ...但在一个查询中有两个SELECT ...

喜欢什么?

 SELECT SUM(Amount) AS SumAmount
 WHERE Amount < 210
 GROUP BY Name

 SELECT Name, SUM(Amount)
 WHERE SumAmount >= 210
 GROUP BY Name

请,建议

1 个答案:

答案 0 :(得分:3)

使用HAVING子句过滤汇总结果,例如SUM()

SELECT Name, SUM(Amount)
FROM   tableName
WHERE  Amount < 210
GROUP  BY Name
HAVING SUM(Amount) >= 210