【问题标题】:Unpivot in Potgresql在 Postgresql 中反透视
【发布时间】:2017-08-30 01:00:00
【问题描述】:

如何在不使用 UNION 的情况下在 Postgresql 中进行反透视?我有超过 100 列,我正在寻找一种简洁的方法来完成它。

给定表:

id    c1      c2      c3
1      X       Y       Z
2      A       B       C
3      Y       C       Z

想要的表:

id   col
1     X
1     Y
1     Z
2     A
2     B
2     C
3     Y
3     C
3     Z

【问题讨论】:

    标签: sql postgresql unpivot


    【解决方案1】:

    使用jsonb functions:

    select id, value as col
    from my_table
    cross join jsonb_each_text(to_jsonb(my_table))
    where key <> 'id';
    
     id | value 
    ----+-------
      1 | X
      1 | Y
      1 | Z
      2 | A
      2 | B
      2 | C
      3 | Y
      3 | C
      3 | Z
    (9 rows)
    

    Db<>Fiddle.


    在 Postgres 9.3 或 9.4 中使用 to_json()json_each_text()

    在 9.1 或 9.2 版本中安装 hstore:

    create extension if not exists hstore;
    
    select id, value as col
    from my_table
    cross join each(hstore(my_table))
    where key <> 'id';
    

    【讨论】:

    • 谢谢@klin。我收到以下错误:函数 to_jsonb(my_table) 不存在。你知道为什么会这样吗?
    • 该功能在 Postgres 9.5+ 中可用;如果您有 9.3 或 9.4 版,请使用 json_each_text()to_json()
    • 谢谢,但遇到同样的错误。会不会是我的 postgres 安装丢失了什么?
    • 你的 Postgres 版本是多少?
    • 现在是 9.2。大概就是这个原因吧!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    相关资源
    最近更新 更多