转置生成系列日期postgresql

时间:2016-01-06 08:28:18

标签: postgresql postgresql-9.1

以前曾多次询问有关转置的问题,但在使用generate_series和date时我找不到任何好的答案,因为列可能会有所不同。

WITH range AS
(SELECT to_char(generate_series('2015-01-01','2015-01-05', interval '1 day'),'YYYY-MM-DD'))
SELECT * FROM range; 

generate系列的正常输出是:

2015-12-01
2015-12-02
2015-12-03
... and so on 

http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/5478

但我希望它是专栏

2015-12-01  2015-12-02  2015-12-03  ...and so on

似乎交叉表可能应该做的伎俩,但我只会得到错误:

select * from crosstab('(SELECT to_char(generate_series('2015-01-01','2015-01-05', interval '1 day'),'YYYY-MM-DD'))')
as ct (dynamic columns?)

如何动态地使用交叉表生成generate_series(date-date)和不同的间隔?

TIA

1 个答案:

答案 0 :(得分:1)

参考链接PostgreSQL query with generated columns

您可以动态生成列:

create or replace function sp_test()
returns void as
$$

declare cases character varying;
declare sql_statement text;
begin
    drop table if exists temp_series;
    create temporary  table temp_series as
    SELECT to_char(generate_series('2015-01-01','2015-01-02', interval '1 day'),'YYYY-MM-DD') as series;

    select string_agg(concat('max(case when t1.series=','''',series,'''',' then t1.series else ''0000-00-00'' end) as ','"', series,'"'),',') into cases from temp_series;

    drop table if exists temp_data;
    sql_statement=concat('create temporary table temp_data as select ',cases ,' 
    from temp_series t1');

    raise notice '%',sql_statement;
    execute sql_statement;
end;
$$
language 'plpgsql';

以下列方式调用函数以获得输出:

select sp_test(); select * from temp_data;

更新的功能需要两个日期参数:

create or replace function sp_test(start_date timestamp without time zone,end_date timestamp without time zone)
returns void as
$$

declare cases character varying;
declare sql_statement text;
begin
    drop table if exists temp_series;
    create temporary  table temp_series as
    SELECT to_char(generate_series(start_date,end_date, interval '1 day'),'YYYY-MM-DD') as series;

    select string_agg(concat('max(case when t1.series=','''',series,'''',' then t1.series else ''0000-00-00'' end) as ','"', series,'"'),',') into cases from temp_series;

    drop table if exists temp_data;
    sql_statement=concat('create temporary table temp_data as select ',cases ,' 
    from temp_series t1');

    raise notice '%',sql_statement;
    execute sql_statement;
end;
$$
language 'plpgsql';

函数调用:

select sp_test('2015-01-01','2015-01-10'); select * from temp_data;