gpt4 book ai didi

sql - PostgreSQL 中的逆透视表

转载 作者:行者123 更新时间:2023-12-04 13:11:53 25 4
gpt4 key购买 nike

由于 SUM(Case....End),我有下表。

Account            Product_A            Product_B           Product_C
101 1000 2000 3000
102 2000 1000 0
103 2000 1000 0
104 2000 1000 2000
我想把它放回原来的 table 。像这样:
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;
Online example

关于sql - PostgreSQL 中的逆透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64268037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com