【问题标题】:Convert rows to columns by same column value in Postgres在 Postgres 中通过相同的列值将行转换为列
【发布时间】:2020-11-14 13:37:40
【问题描述】:

我有一张这样的桌子:

id     name    value
--------------------
1      x       100
1      y       200
1      z       300
2      x       10
2      y       abc
2      z       001
3      x       1
...
--------------------

我需要把它变成这样的东西:

id    x     y     z
---------------------
1     100   200   300
2     10    abc   001
3     1     ...
---------------------

名称已确定。我可以进行多个联接,但我正在寻找更优雅的解决方案。

【问题讨论】:

    标签: sql postgresql pivot crosstab


    【解决方案1】:

    使用条件聚合,在 Postgres 中使用 filter 语法:

    select id,
           max(value) filter (where name = 'x') as x,
           max(value) filter (where name = 'y') as y,
           max(value) filter (where name = 'z') as z
    from t
    group by id;
    

    【讨论】:

      【解决方案2】:

      附加模块tablefunc 提供crosstab() 函数的变体,通常最快:

      SELECT *
      FROM   crosstab(
         'SELECT id, name, value
          FROM   tbl
          ORDER  BY 1, 2'
         ) AS ct (id int, x text, y text, z text);
      

      您的value 中似乎混合了数字和字符串,因此我选择了text 作为输出。

      见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-03
        • 1970-01-01
        • 2021-11-15
        • 1970-01-01
        • 1970-01-01
        • 2016-10-06
        • 2021-10-22
        • 1970-01-01
        相关资源
        最近更新 更多