PostgreSQL中的Unpivot表

PostgreSQL中的Unpivot表,sql,postgresql,unpivot,Sql,Postgresql,Unpivot,我有下表作为SUM(案例…结束)的结果 我想把它放回原来的桌子上。像这样: Account Product Qty 101 A 1000 ... .. .... 我认为“Unpivot”可以在MS SQL Server中实现。但我只使用PostgreSQL。 在Postgresql中,可以返回/取消对上表分组的Unpivot的等价

我有下表作为SUM(案例…结束)的结果

我想把它放回原来的桌子上。像这样:

Account         Product               Qty
101               A                  1000
...               ..                 ....
我认为“Unpivot”可以在MS SQL Server中实现。但我只使用PostgreSQL。 在Postgresql中,可以返回/取消对上表分组的Unpivot的等价物是什么?
谢谢

您可以将横向联接与values子句一起使用:

select t.account, u.product, u.qty
from the_table t
  cross join lateral ( 
     values ('A',product_a), ('B', product_b), ('C', product_c)
  ) as u(product, qty)
order by t.account;

我认为简单的
unest
将帮助您:

SELECT Account,
       unnest(array['A', 'B', 'C']) AS Product,
       unnest(array[Product_A, Product_B, Product_C]) AS Qty
FROM test
ORDER BY Account;

即使通过使用JSON函数向表中添加了更多列(如
Product\u D
),也可以动态取消对这些列的IVOT:

SELECT account, UPPER(SPLIT_PART((js).key, '_', 2)) AS Product, (js).value AS Qty 
  FROM( SELECT rj->>'account' AS Account, JSON_EACH_TEXT(rj) AS js
          FROM ( SELECT ROW_TO_JSON(t) AS rj FROM t) AS q1 ) AS q2
 WHERE (js).key != 'account';

根据为现有列名(
Product\u A/B/C
)定义的模式拆分产品的列名,而不明确指定每个字母

SELECT account, UPPER(SPLIT_PART((js).key, '_', 2)) AS Product, (js).value AS Qty 
  FROM( SELECT rj->>'account' AS Account, JSON_EACH_TEXT(rj) AS js
          FROM ( SELECT ROW_TO_JSON(t) AS rj FROM t) AS q1 ) AS q2
 WHERE (js).key != 'account';