简体   繁体   English

使用generate_series的动态交叉表

[英]Dynamic crosstab using generate_series

Trying to do a dynamic crosstab using generate_series. 尝试使用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" “ SELECT”处或附近的语法错误

Why? 为什么? Any tip how to do this dynamic in a simple way? 任何技巧如何以一种简单的方式实现这种动态? (Preferable without using functions) (最好不使用功能)

TIA, 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). 选择列表并以服务器端非SQL语言动态生成查询(我会选择plpgsql或plperl)。

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. 现在,第一种方法比较干净,因为第二种方法可以解决问题,因此您可能必须返回一个refcursor并从中获取,因为计划人员需要在返回函数之前先知道函数的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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