表:
id | c1 | c2
-------------
1 | 10 | 20
2 | 55 | 20
3 | 30 | 30
4 | 11 | 80
5 | 12 | 20
并查询
select (sum(c1)+sum(c2))as sum from mytable where sum > 100 ??
上面生成的错误是sum,而不是表的一部分。有什么办法可以限制/在哪里条件限制返回的结果仅在两列求和的条件下?(不需要在表中添加第三列)
感谢
我相信您正在寻找HAVING
子句。
所以,
SELECT (SUM(c1)+SUM(C2)) AS sum FROM mytable HAVING sum > 100;
您可以将现有查询包装在另一个选择中:
select total
from
(
select sum(c1 + c2) as total
from mytable
) d
where total > 100;
或者你可以使用HAVING提示:
select sum(c1 + c2) as total
from mytable
having sum(c1 + c2) > 100; -- you can also use the total alias in the having
请参阅SQL Fiddle with Demo。
这个答案与Ahmed的评论有关:
SELECT (c1+c2) AS sum FROM mytable WHERE ID > 5 GROUP BY ID HAVING sum > 100;