如何在postgres中旋转多列

How to pivot multiple columns in postgres

我在 Postgres 中有一个 table,我想在 2 列上从宽到长旋转。

数据源太大,无法使用 Python,因为这需要加载到内存中。 Postgres 中是否有一个函数可以做到这一点?

下面是 table 的样子...

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

输出应如下所示:

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

如有任何想法,我们将不胜感激。

使用联合查询:

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;