-1

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

iskandarblue
  • 7,208
  • 15
  • 60
  • 130
  • 2
    If you want dynamic columns, then you need dynamic SQL - which is more complicated than pure SQL. – GMB Dec 30 '20 at 17:32
  • Does this answer your question? [PostgreSQL 9.3: Dynamic pivot table](https://stackoverflow.com/questions/28337765/postgresql-9-3-dynamic-pivot-table) – astentx Dec 30 '20 at 17:35

1 Answers1

0

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;