Ben Sharkey
Ben Sharkey

Reputation: 313

How to pivot multiple columns in postgres

I have a table in Postgres that I want to pivot from wide to long on 2 columns.

The data source is too large to be able to use Python as this would require loading to memory. Is there a function in Postgres that is able to do this?

Below is what the table looks like...

date        a1_on_time      a1_days b2_on_time  b2_days
15-Apr-19   TRUE            1       TRUE        1
26-Apr-19   TRUE            2       FALSE       6

The output should look like this:

date        metric   on_time   days
15-Apr-19   a1       TRUE      1
26-Apr-19   a1       TRUE      2
15-Apr-19   b2       TRUE      1
26-Apr-19   b2       FALSE     6

Any ideas would be much appreciated.

Upvotes: 0

Views: 323

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

Use a union query:

select date, 'a1' as metric, a1_on_time as on_time, a1_days as days from your_table
union all
select date, 'b2', b2_on_time, b2_days from your_table
order by metric, date;

Upvotes: 1

Related Questions