假设我有这样的事情:
select sum(points) as total_points
from sometable
where total_points > 25
group by username
Run Code Online (Sandbox Code Playgroud)
我无法total_points在where子句中引用,因为我收到以下错误:ERROR: column "total_points" does not exist.在这种情况下,我sum(points)在where子句中重写没有问题,但是我想要做一些我上面做的事情.
sum(points)在where子句中,是Postgres的足够聪明,不重新计算呢?Qua*_*noi 20
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY
username
HAVING SUM(points) > 25
Run Code Online (Sandbox Code Playgroud)
PostgreSQL 不会计算两次总和.
Nat*_*ler 10
我相信PostgreSQL就像其他品牌的sql一样,你需要做的事情:
SELECT t.*
FROM (
SELECT SUM(points) AS total_points
FROM sometable
GROUP BY username
) t
WHERE total_points > 25
Run Code Online (Sandbox Code Playgroud)
编辑:忘记别名子查询.
您在声明中有错误:
select sum(points) as total_points
from sometable
where total_points > 25 -- <- error here
group by username
Run Code Online (Sandbox Code Playgroud)
您不能限制行数total_points,因为sometable没有该列.你想要的是限制total_points每个组计算的结果行数,所以:
select sum(points) as total_points
from sometable
group by username
having sum(points) > 25
Run Code Online (Sandbox Code Playgroud)
如果你total_point在你的例子中替换,那么只需在所有行计算的总和大于25时,然后返回所有行,按用户名分组.
编辑:
永远记住订单:
FROM用JOIN的拿到表WHERE从表行限制SELECT用于限制列GROUP BY对于组行成有关的组HAVING限制结果组ORDER BY订单结果| 归档时间: |
|
| 查看次数: |
5906 次 |
| 最近记录: |