Postgres:将单行转换为多行(不可透视) [英] Postgres: convert single row to multiple rows (unpivot)

查看:109
本文介绍了Postgres:将单行转换为多行(不可透视)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子:

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中进行选择查询,其结果如下:

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.

推荐答案

带有 LATERAL SELECT $ c>加入 VALUES 表达式即可完成工作:

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

相关:

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

这篇关于Postgres:将单行转换为多行(不可透视)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆