答案 0 :(得分: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
答案 1 :(得分:0)
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分组,然后在其自己的列中选择每个值。出于语法原因,您需要在各个values列上使用一个汇总函数,这就是为什么每个列都具有Max函数的原因。
不是,以标准化的方式存储数据当然会更好。另外,对于较新版本的postgres,您可以使用filter而不是case,我觉得它更具可读性。