简体   繁体   English

参考postgres查询中的动态列?

[英]Referring to dynamic columns in a postgres query?

Let's say I have something like this: 假设我有这样的事情:

select sum(points) as total_points
from sometable
where total_points > 25
group by username

I am unable to refer to total_points in the where clause because I get the following error: ERROR: column "total_points" does not exist . 我无法在where子句中引用total_points ,因为我收到以下错误: ERROR: column "total_points" does not exist In this case I'd have no problem rewriting sum(points) in the where clause, but I'd like some way of doing what I have above. 在这种情况下,我在where子句中重写sum(points)没有问题,但是我想要做一些我上面做的事情。

  • Is there any way to store the result in a variable without using a stored procedure? 有没有办法在使用存储过程的情况下将结果存储在变量中?
  • If I do rewrite sum(points) in the where clause, is postgres smart enough to not recalculate it? 如果我重写sum(points)在where子句中,是Postgres的足够聪明,不重新计算呢?
SELECT  SUM(points) AS total_points
FROM    sometable
GROUP BY
        username
HAVING  SUM(points) > 25

PostgreSQL won't calculate the sum twice. PostgreSQL不会计算两次总和。

I believe PostgreSQL is like other brands of sql, where you need to do: 我相信PostgreSQL就像其他品牌的sql一样,你需要做的事情:

SELECT t.* 
FROM (
    SELECT SUM(points) AS total_points
    FROM sometable
    GROUP BY username
) t
WHERE total_points > 25

EDIT: Forgot to alias subquery. 编辑:忘记别名子查询。

You have error in statement: 您在声明中有错误:

select sum(points) as total_points
from sometable
where total_points > 25 -- <- error here
group by username

You can't limit rows by total_points , because sometable don't have that column. 您不能通过total_points限制行,因为sometable没有该列。 What you want is limit gouped resulting rows by total_points , computed for each group, so: 你想要的是通过total_points限制结果行,为每个组计算,所以:

select sum(points) as total_points
from sometable
group by username
having sum(points) > 25

If you replace total_point in your example, then you simply chech if sum computed from all rows is bigger than 25 and then return all rows, grouped by username. 如果在示例中替换total_point ,那么只需在所有行计算的总和大于25的情况下进行切换,然后返回按用户名分组的所有行。

Edit: 编辑:
Always remember order: 永远记住订单:

  1. is FROM with JOIN 's to get tables JOINFROM是获取表格
  2. is WHERE for limit rows from tables 是来自表的限制行的WHERE
  3. is SELECT for limit columns 是限制列的SELECT
  4. is GROUP BY for group rows into related groups GROUP BY用于将组行分组到相关组中
  5. is HAVING for limit resulting groups HAVING用于限制产生的基团
  6. is ORDER BY for order results 订单结果是ORDER BY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM