代码之家  ›  专栏  ›  技术社区  ›  ryeguy

在Postgres查询中引用动态列?

  •  15
  • ryeguy  · 技术社区  · 16 年前

    假设我有这样的东西:

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

    我不能参考 total_points 在WHERE子句中,因为我得到以下错误: ERROR: column "total_points" does not exist . 在这种情况下,我可以很好地重写 sum(points) 在WHERE子句中,但是我想用某种方法来做我上面提到的事情。

    • 有没有办法把结果存储在变量中 没有 使用存储过程?
    • 如果我 重写 总和(分) 在WHERE子句中,Postgres是否足够聪明,不需要重新计算它?
    3 回复  |  直到 9 年前
        1
  •  10
  •   Nathan Wheeler    16 年前

    我相信PostgreSQL和其他SQL品牌一样,您需要这样做:

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

    编辑:忘记别名子查询。

        2
  •  18
  •   Quassnoi    16 年前
    SELECT  SUM(points) AS total_points
    FROM    sometable
    GROUP BY
            username
    HAVING  SUM(points) > 25
    

    PostgreSQL 不会计算两次。

        3
  •  7
  •   MBO    16 年前

    语句中有错误:

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

    不能限制行数 total_points ,因为 sometable 没有那个专栏。您需要的是将结果行限制为 总分 ,为每个组计算,因此:

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

    如果你替换 total_point 在您的示例中,如果从所有行计算出的和大于25,则只需勾选,然后返回按用户名分组的所有行。

    编辑:
    始终记住顺序:

    1. FROM 具有 JOIN 去拿桌子
    2. WHERE 用于限制表中的行
    3. SELECT 对于限制列
    4. GROUP BY 将行分组为相关组
    5. HAVING 对于限制结果组
    6. ORDER BY 订单结果