【问题标题】:How to transform rows to columns using Postgres SQL?如何使用 Postgresql 将行转换为列?
【发布时间】:2019-07-14 01:16:44
【问题描述】:

我有以下结构中的数据

期望的输出

【问题讨论】:

  • 为什么是 MySQL 标签?

标签: sql postgresql pivot crosstab postgresql-9.4


【解决方案1】:

Postgres(从 9.4 开始)支持条件聚合的 filter 语法。所以我会推荐:

SELECT customer_id,
       MAX(value) FILTER (WHERE name = 'age') as age,
       MAX(value) FILTER (WHERE name = 'marketing_consent') as marketing_consent,
       MAX(value) FILTER (WHERE name = 'gender') as gender
FROM t
GROUP BY customer_id

【讨论】:

    【解决方案2】:
    SELECT customer_id,
        MAX(CASE WHEN name='age' THEN value ELSE NULL END) AS age,
        MAX(CASE WHEN name='marketing_consent' THEN value ELSE NULL END) AS marketing_consent,
        MAX(CASE WHEN name='gender' THEN value ELSE NULL END) AS gender
    FROM table
    GROUP BY customer_id;
    

    您只需按 customer_id 分组并在其自己的列中选择每个值。出于语法原因,您需要在各种值列上使用聚合函数,这就是每列都有一个 Max 函数的原因。

    请注意,以标准化方式存储数据当然会更好。此外,对于较新版本的 postgres,您可以使用过滤器而不是大小写,我发现它更具可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 2012-12-14
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2014-06-26
      相关资源
      最近更新 更多