Postgres:将单行转换为多行(逆轴)
Postgres: convert single row to multiple rows (unpivot)
我有一个 table:
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 中进行 select 查询,它给出的结果如下:
---------------------------
| 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 |
...
非常感谢任何有关类似示例链接的帮助。
试一试:
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 所建议的那样,并集是 select DISTINCT
值的方式,因为这里会是 UNION ALL
首选 - 以防万一(我不知道 id 是否唯一)
当然,如果是英国 - 不会有任何区别
带有 LATERAL
连接到 VALUES
表达式的单个 SELECT
完成工作:
SELECT p.id, v.*
FROM price_list p
, LATERAL (
VALUES
('type_a', p.price_type_a)
, ('type_b', p.price_type_b)
, ('type_c', p.price_type_c)
) v (price_type, price);
相关:
- Convert one row into multiple rows with fewer columns
- SELECT DISTINCT on multiple columns
我有一个 table:
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 中进行 select 查询,它给出的结果如下:
---------------------------
| 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 |
...
非常感谢任何有关类似示例链接的帮助。
试一试:
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 所建议的那样,并集是 select DISTINCT
值的方式,因为这里会是 UNION ALL
首选 - 以防万一(我不知道 id 是否唯一)
当然,如果是英国 - 不会有任何区别
带有 LATERAL
连接到 VALUES
表达式的单个 SELECT
完成工作:
SELECT p.id, v.*
FROM price_list p
, LATERAL (
VALUES
('type_a', p.price_type_a)
, ('type_b', p.price_type_b)
, ('type_c', p.price_type_c)
) v (price_type, price);
相关:
- Convert one row into multiple rows with fewer columns
- SELECT DISTINCT on multiple columns