Dynamically execute query using the output of another query

こ雲淡風輕ζ 提交于 2019-12-02 02:02:41

You can do this with a plain SELECT query using the new LATERAL JOIN in Postgres 9.3+

SELECT *
FROM  (
   SELECT max(rundate) AS rundate, branch
   FROM   t_index_of_imported_files
   GROUP  BY branch
   ) t
 , generate_table(t.rundate, t.branch) g;  -- LATERAL is implicit here

Per documentation:

LATERAL can also precede a function-call FROM item, but in this case it is a noise word, because the function expression can refer to earlier FROM items in any case.

The same is possible in older versions by expanding rows for set-returning functions in the SELECT list, but the new syntax with LATERAL is much cleaner. Anyway, for Postgres 9.2 or older:

SELECT generate_table(max(rundate), branch)
FROM   t_index_of_imported_files
GROUP  BY branch;
select generate_table(max(rundate) as rundate, branch)
from t_index_of_imported_files
group by branch

No need to do anything too fancy.

SELECT generate_table(rundate,branch) FROM (
    SELECT max(rundate) AS rundate, branch
    FROM t_index_of_imported_files
    GROUP BY branch) x;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!