简体   繁体   中英

Dynamic crosstab using generate_series

Trying to do a dynamic crosstab using generate_series. But with no luck.

This "STATIC" query works as expected:

SELECT * FROM crosstab(
$$ SELECT DISTINCT ON(sign,date) sign,date,sum(hr) FROM hr $$,
$$ SELECT * FROM(SELECT to_char(generate_series('2014-01-01','2014-01-05', interval '1 day'),'YYYY-MM-DD') date )date$$) 
as ct (sign text,"2014-01-01" text,"2014-01-02" text,"2014-01-03" text,"2014-01-04" text,"2014-01-05" text)

This last part I want to replace with a dynamic query:

sign text,"2014-01-01" text,"2014-01-02" text,"2014-01-03" text,"2014-01-04" text,"2014-01-05" text

I have managed to created this by:

SELECT concat('sign text,',(SELECT string_agg(col,',') from( select to_char(generate_series('2015-01-01','2015-01-05', interval '1 day'),'\"YYYY-MM-DD\" text')col )cols))

Which generates the same text as above. Replacing this "STATIC" text with this "DYNAMIC" query does not work:

SELECT * FROM crosstab(
$$ SELECT DISTINCT ON(sign,date) sign,date,sum(hr) FROM hr $$,
$$ SELECT * FROM(SELECT to_char(generate_series('2014-01-01','2014-01-05', interval '1 day'),'YYYY-MM-DD') date )date$$) 
as ct (SELECT concat('sign text,',(SELECT string_agg(col,',') from( SELECT to_char(generate_series('2015-01-01','2015-01-05', interval '1 day'),'\"YYYY-MM-DD\" text')col )cols)))

syntax error at or near "SELECT"

Why? Any tip how to do this dynamic in a simple way? (Preferable without using functions)

TIA,

The problem here is that the planner needs to know the row size before planning. So you have a few options:

  1. select the list and dynamically generate the query in a client-side language or
  2. select the list and dynamically generate the query in a server-side non-SQL language (plpgsql or plperl would be my choices).

Now, the first is cleaner because the second just shifts the problem and so you would probably have to return a refcursor and fetch from that since the planner needs to know the output of the function before returning it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM