简体   繁体   English

如何使用 Postgres SQL 将行转换为列?

[英]How to transform rows to columns using Postgres SQL?

I have the data in the following structure我有以下结构的数据题

Desired Output期望输出

https://imgur.com/a/855njBn][1]

Postgres (starting in 9.4) supports the filter syntax for conditional aggregation. Postgres(从 9.4 开始)支持条件聚合的filter语法。 So I would recommend:所以我会推荐:

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

You just group by customer_id and pick out each value in its own column.您只需按 customer_id 分组并在其自己的列中挑选每个值。 You need an aggregate function on the various values columns for syntactical reasons, which is why each column has a Max function.出于语法原因,您需要在各种值列上使用聚合函数,这就是为什么每列都有一个 Max 函数的原因。

Not e that it would of course be better to store the data in a normalized fashion.并不是说以规范化的方式存储数据当然会更好。 Also, with newer versions of postgres, you can use filter instead of case, which I find a bit more readable.此外,对于较新版本的 postgres,您可以使用过滤器而不是大小写,我发现它更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM