簡體   English   中英

取消嵌套列並根據 Postgres 中未嵌套的列合並行

[英]unnest a column and merge rows based on the unnested column in Postgres

我有一張這樣的桌子:

ID A的價格 B的價格 C的價格 D的價格
A,B,C 1個 2個 3個 null
null null null 4個
null 10 null null

我想要實現的目標:

ID 價格
一種 1個
2,10
C 3個
4個

我嘗試unnest(string_to_array(ID,','))然后concat_ws(',', "A's price", "B's price", "C's price", "D's price") ,它沒有給我想要的 output .

有沒有辦法在 Postgres 中實現這一點,或者我需要切換到 pandas?

感謝任何想法和建議!

首先 - 這種數據設計很糟糕。 考慮規范化(至少 1NF),然后查詢會簡單得多。
展平t子查詢中的表,然后按個人id分組並重新聚合。

-- Test data
create table the_table 
(
 id text, 
 aprice numeric, 
 bprice numeric, 
 cprice numeric, 
 dprice numeric
);
insert into the_table values
('A,B,C', 1,    2,    3,    null),
('D',     null, null, null, 4),
('B',     null, 10,   null, null);

-- Query
select id,
  string_agg (case id 
     when 'A' then aprice 
     when 'B' then bprice 
     when 'C' then cprice
     when 'D' then dprice 
     end ::text, ',') as price
from
(
  select unnest(string_to_array(id, ',')) as id, aprice, bprice, cprice, dprice
  from the_table
) as t
group by id order by id; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM