[英]Postgres: convert single row to multiple rows (unpivot)
I have a 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 |
---------------------------------------------------
I need a select query in Postgres which gives result like this: 我在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 |
...
Any help with links to similar examples greatly appreciated. 任何有关类似示例链接的帮助都非常感谢。
A single SELECT
with a LATERAL
join to a VALUES
expression does the job: 使用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);
Related: 有关:
try smth like: 尝试smth像:
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
;
update as a_horse_with_no_name suggests, union is way to select DISTINCT
values, for here would be UNION ALL
prefered - just in case (I don't know if id is UNIQUE) 更新为a_horse_with_no_name建议,union是选择DISTINCT
值的方法,因为这里首选UNION ALL
- 以防万一(我不知道id是否为UNIQUE)
Of course if it is UK - there will be no difference 当然,如果是英国 - 也没有区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.