我尝试根据两个聚合列进行排序
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/