sql - 按顺序找不到聚合列

标签 sql postgresql

我尝试根据两个聚合列进行排序

SELECT  count(ids) as no_of_ids , sum((rate > 0)::int)as right_count
From  profile_performance
group By  p.profile_id
Order by  (right_count/predictions) desc limit 10 

我得到的错误是:

ERROR:  column "right_count" does not exist
LINE 6: Order by  (right_count/no_of_ids::float) desc limit 10
               ^
********** Error **********

ERROR: column "right_count" does not exist
SQL state: 42703
Character: 413

但以下工作正常:

SELECT  count(ids) as no_of_ids , sum((rate > 0)::int)as right_count
From  profile_performance
group By  p.profile_id
Order by  right_count,predictions desc limit 10 

是否可以在不使用外部查询的情况下修复它?

最佳答案

你应该能够重复表达:

SELECT  count(ids) as no_of_ids , sum((rate > 0)::int) as right_count
From  profile_performance
group By  p.profile_id
Order by  (sum((rate > 0)::int) / predictions) desc
limit 10 ;

显然,Postgres 允许您在order by 中引用列别名。但是,它无法识别包含它们的表达式。

这更清楚documented :

Note that an output column name has to stand alone, that is, it cannot be used in an expression — for example, this is not correct:

SELECT a + b AS sum, c FROM table1 ORDER BY sum + c;          -- wrong

This restriction is made to reduce ambiguity. There is still ambiguity if an ORDER BY item is a simple name that could match either an output column name or a column from the table expression. The output column is used in such cases. This would only cause confusion if you use AS to rename an output column to match some other table column's name.

关于sql - 按顺序找不到聚合列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45869219/

相关文章:

php - 我需要帮助更新特定用户的 sql 条目

sql - PostgreSQL 找到 CREATE TABLE 语句

sql - 无法在 jsonb 对象字段中搜索文本

sql - SQL 查询中的多个 Select 语句

sql - 将 Datetime 格式转换为 varchar 格式样式的解决方法

ruby-on-rails-3 - 如何使用 Datamapper 迁移调整 postgreSQL 数据库中的列长度?

mysql - 从 SQL hasmany 关系构造嵌套对象图

java - 在Java中获取没有时区的时间

MySql 查询 - 基于条件需要 'ORDER BY' 选项

SQL 按查询中指定的顺序排序