Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

sql - Postgres pivot without crosstab

I am using a Postgres instance with relatively limited functionality - for example, the crosstab() function is not available. My objective is to pivot a table so that dates in ym are arranged as columns in ascending order by date, for example:

input:

group_code  ym  total
foo 2020-11-01  17
foo 2020-12-01  19
bar 2020-09-01  21
baz 2020-10-01  23

output:

group_code 2020-09-01 2020-10-01 2020-11-01 2020-12-01
foo        NULL       NULL       17         19
bar        21         NULL       NULL       NULL
baz        NULL       23         NULL       NULL

The key here, however, is that the number of unique dates is not known in advance, and that group codes without values for a specific date should be NULL in the resulting table. Is there an elegant workaround in postgres to create such an output table without hardcoding all of the dates in advance with CASE WHEN statements and FULL OUTER JOINs - in other words - dynamically? Any suggestions would be appreciated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use filtered aggregation:

select group_code, 
       max(total) filter (where ym = date '2020-09-01') as "2020-09-01",
       max(total) filter (where ym = date '2020-10-01') as "2020-10-01",
       max(total) filter (where ym = date '2020-11-01') as "2020-11-01",
       max(total) filter (where ym = date '2020-12-01') as "2020-11-02"
from the_table
group by group_code;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...