Postgres:将单行转换为多行(逆轴)

问题描述 投票:0回答:2

我有一张桌子:

Table_Name: price_list
---------------------------------------------------
| id | price_type_a | price_type_b | price_type_c |
---------------------------------------------------
| 1  |    1234      |     5678     |     9012     |
| 2  |    3456      |     7890     |     1234     |
| 3  |    5678      |     9012     |     3456     |
---------------------------------------------------

我需要在 Postgres 中进行选择查询,它给出的结果如下:

---------------------------
| id | price_type | price |
---------------------------
| 1  |  type_a    | 1234  |
| 1  |  type_b    | 5678  |
| 1  |  type_c    | 9012  |
| 2  |  type_a    | 3456  |
| 2  |  type_b    | 7890  |
| 2  |  type_c    | 1234  |
...

非常感谢任何有关类似示例链接的帮助。

sql database postgresql data-manipulation unpivot
2个回答
13
投票

带有

SELECT
连接到
LATERAL
表达式的单个
VALUES
完成“取消旋转”列以分隔行的工作:

SELECT p.id, v.*
FROM   price_list p
CROSS  JOIN LATERAL (
   VALUES
      ('type_a', p.price_type_a)
    , ('type_b', p.price_type_b)
    , ('type_c', p.price_type_c)
   ) v (price_type, price);

相关:


0
投票

试一试:

select id, 'type_a',type_a  from price_list
union all
select id, 'type_b',type_b  from price_list
union all
select id, 'type_c',type_c  from price_list
;

更新 正如 a_horse_with_no_name 所建议的那样,union 是选择

DISTINCT
值的方式,因为这里是
UNION ALL
首选 - 以防万一(我不知道 id 是否唯一)

当然,如果是英国 - 就没有区别

© www.soinside.com 2019 - 2024. All rights reserved.