Dynamically execute query using the output of another query

后端 未结 3 549
醉话见心
醉话见心 2021-01-21 18:13

I have a function called generate_table, that takes 2 input parameters (rundate::date and branch::varchar)

Now I am trying to work on a second

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-21 18:42

    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;
    

提交回复
热议问题