简体   繁体   English

如何转置 postgresql 中的表值?

[英]How can I transpose table values in postgresql?

How can I transpose these values to take this table:如何转置这些值以获取此表:

在此处输入图像描述

And make it look like this:让它看起来像这样:

在此处输入图像描述

There's no Pivot function that I can use in postgresql and every time I try the crosstab function, I keep getting an error in my code. There's no Pivot function that I can use in postgresql and every time I try the crosstab function, I keep getting an error in my code. Let's pretend that my table is called select * from TAttributes假设我的表名为 select * 来自 TAttributes

Use conditional aggregation, which in Postgres means filter :使用条件聚合,在 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;

Here is a db<>fiddle. 是一个 db<>fiddle。

Try this:尝试这个:

SELECT id,  
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2000)) AS '2000',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2001)) AS '2001',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2002)) AS '2002',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2003)) AS '2003' 
FROM public.t ext_t GROUP BY id

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

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