让我说我有这样的事情:
select sum(points) as total_points
from sometable
where total_points > 25
group by username
我无法在where子句中引用total_points
,因为我收到以下错误:ERROR: column "total_points" does not exist
。在这种情况下,我在where子句中重写sum(points)
没有问题,但我想要一些方法来做我上面的事情。
sum(points)
,postgres是否足够聪明,不会重新计算它?答案 0 :(得分:20)
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY
username
HAVING SUM(points) > 25
PostgreSQL
不会计算两次总和。
答案 1 :(得分:10)
我相信PostgreSQL就像其他品牌的sql一样,你需要做的事情:
SELECT t.*
FROM (
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY username
) t
WHERE total_points > 25
编辑:忘记别名子查询。
答案 2 :(得分:8)
声明中有错误:
select sum(points) as total_points
from sometable
where total_points > 25 -- <- error here
group by username
您不能按total_points
限制行,因为sometable
没有该列。你想要的是限制每个组计算出的结果行total_points
,所以:
select sum(points) as total_points
from sometable
group by username
having sum(points) > 25
如果在示例中替换total_point
,那么只需在所有行计算的总和大于25时,然后返回按用户名分组的所有行。
编辑:
永远记住订单:
FROM
JOIN
来获取表格WHERE
对于限制列SELECT
GROUP BY
,用于将组行划分为相关组HAVING
ORDER BY