首页 > 解决方案 > 如何在 postgresql 中转置表值?

问题描述

如何转置这些值以获取此表:

在此处输入图像描述

让它看起来像这样:

在此处输入图像描述

在 postgresql 中没有可以使用的 Pivot 函数,每次尝试交叉表函数时,我的代码中都会出现错误。假设我的表名为 select * from TAttributes

标签: sqlpostgresqlpivotcrosstab

解决方案


使用条件聚合,在 Postgres 中意味着filter

select id,
       max(attributenumber) filter (where attributeid = 2000),
       max(attributenumber) filter (where attributeid = 2001),
       max(attributenumber) filter (where attributeid = 2002),
       max(attributenumber) filter (where attributeid = 2003)
from t
group by id;

是一个 db<>fiddle。


推荐阅读