postgresql: 在 select 中使用聚合辅助函数的结果

postgresql: use result from aggregate auxiliary function in select

在辅助函数中,我使用聚合函数 (count) 因此它只给出一个结果,没有列。 稍后,我想在我的查询中使用该函数的结果:

with total as  (select count(*) from employees)
select emp_no, (cast (rank() over (order by emp_no) as Float))/total
from employees

但是,这会产生错误:

column "total" does not exist

我将错误解释为:需要将单个(聚合)结果转换为一列。我该如何解决这个问题?有没有办法(有效地)解决这个问题?

我阅读了多个关于 WITH 的参考文献(例如 https://www.tutorialspoint.com/postgresql/postgresql_with_clause.htm),但总是在 WITH 子句中创建了一个 table,而不是单个值,如我的情况。

but there is always a table created in the WITH clause., not a single value as in my case.

CTE 总是 创建一个 "table"。即使是您的 CTE - 碰巧您的 CTE 总是恰好包含一列和一行。


错误的原因是您的最终查询没有引用名为 total 的 CTE,因此无法访问它(或其列)。

您需要在最终 SELECT 声明的 from 子句中包含 CTE total

with total as (
  select count(*) as emp_count
  from employees
)
select emp_no, (cast (rank() over (order by emp_no) as Float)) / emp_count
from employees
  cross join total;

如果将计数转换为数字(或浮点数)类型,则可以简化最终 SELECT 中的表达式:

with total as (
  select count(*)::float as emp_count
  from employees
)
select emp_no, 
       rank() over (order by emp_no) / emp_count
from employees
  cross join total;