簡體   English   中英

如何轉置 postgresql 中的表值?

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

如何轉置這些值以獲取此表:

在此處輸入圖像描述

讓它看起來像這樣:

在此處輸入圖像描述

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. 假設我的表名為 select * 來自 TAttributes

使用條件聚合,在 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。

嘗試這個:

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