簡體   English   中英

Postgres:將單行轉換為多行(unpivot)

[英]Postgres: convert single row to multiple rows (unpivot)

我有一張桌子:

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

任何有關類似示例鏈接的幫助都非常感謝。

使用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);

有關:

嘗試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
;

更新為a_horse_with_no_name建議,union是選擇DISTINCT值的方法,因為這里首選UNION ALL - 以防萬一(我不知道id是否為UNIQUE)

當然,如果是英國 - 也沒有區別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM