Postgres: convert single row to multiple rows (unpivot)

孤人 提交于 2019-12-29 08:47:04

问题


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:

---------------------------
| 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.


回答1:


A single SELECT with a LATERAL join to a VALUES expression does the job:

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:

  • Convert one row into multiple rows with fewer columns
  • SELECT DISTINCT on multiple columns



回答2:


try smth like:

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)

Of course if it is UK - there will be no difference



来源:https://stackoverflow.com/questions/47077068/postgres-convert-single-row-to-multiple-rows-unpivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!