在 PostgreSQL 中将列数据转换为行

Convert columns data into rows in PostgreSQL

我有以下格式的数据。

order_no    rate       jan        feb       mar     ....
 1           1200                  2         4
 2           1000      1                     5
 3           2400      14          3          

现在我想转置这个 table 以获得以下输出。

order_no    rate       month     unit
 1           1200       feb       2 
 1           1200       mar       4 
 2           1000       jan       1
 2           2400       mar       5  and so on..

我该怎么做?

一种简单的方法使用 UNION:

SELECT order_no, rate, 'jan' AS month, jan AS unit UNION ALL
SELECT order_no, rate, 'feb', feb UNION ALL
...
SELECT order_no, rate, 'dec', dec
ORDER BY order_no;

Postgres 还具有 CROSSTAB 功能。但是要使用它,你必须非常擅长 SQL,而我不是。

试试这个

Select  order_no, rate, 'jan' as month, jan as unit
from tbl
where jan is not null
union all
Select  order_no, rate, 'feb' as month, feb as unit
from tbl
where feb is not null
union all
Select  order_no, rate, 'mar' as month, mar as unit
from tbl
where mar is not null
order by order_no

您可以使用交叉联接在数据上创建 "temporary" 规范化视图:

select o.order_no, o.rate, v.*
from orders o
  cross join lateral (
      values 
        ('jan', jan), 
        ('feb', feb), 
        ('mar', mar), 
        ... 
        ('dec', dec)
  ) as v(month, unit)

如果要排除没有值的月份,可以添加

where v.unit is not null

到查询

在线示例:http://rextester.com/PBP46544