PostgreSQL重用函数调用结果

时间:2014-03-06 18:54:35

标签: postgresql

我想在PostgreSQL中重用一个昂贵的函数调用:

SELECT name,
  expensive_function(bar) as bars,
  array_length(bars) as total
FROM foos
GROUP BY name

但当然bars不是列,因此会引发以下错误:

ERROR:  column "bars" does not exist

是否有一种语法或技巧可以使其发挥作用?

1 个答案:

答案 0 :(得分:1)

公用表表达式(CTE)可以工作:

WITH subqry AS
  ( SELECT expensive_function(bar) AS bars
    FROM   foos )
SELECT bars,
       array_length(bars)
FROM   subqry;