Postgres: convert single row to multiple rows (unpivot)

前端 未结 2 885
离开以前
离开以前 2020-12-21 01:27

I have a table:

Table_Name: price_list
---------------------------------------------------
| id | price_type_a | price_type_b | price_type_c |
--------------         


        
相关标签:
2条回答
  • 2020-12-21 01:51

    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

    0 讨论(0)
  • 2020-12-21 02:01

    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
    0 讨论(0)
提交回复
热议问题