为每个 id 将行旋转到列

Pivoting rows to columns for each id

我想在 Postgres 10 中将行转为列。

这是 db-fiddle 上的示例数据:

我想实现如下输出:

这是 unpivoting 并且横向连接是一种方便的方法。据推测,您希望结果集中的 id 与原始数据中的 id 相同:

select t.id, v.bin, v.sales
from t cross join lateral
     (values ('bin1', bin1), ('bin2', bin2), ('bin3', bin3)
     ) v(bin, sales);

Here 是一个 db<>fiddle.