如何在 PostgreSQL 中将一列拆分为多列

问题描述 投票:0回答:1

如何在 PostgreSQL 中使用分隔符将一列拆分为多列以返回所有部分
例如。如果 A 列少于 2 行 苹果橙 苹果-葡萄-甜瓜

我希望他们按如下方式分开 第 1 栏 |第 2 栏 |第 3 栏 苹果|橙子| 苹果|葡萄|甜瓜

Split_part 函数仅返回列的一部分,但我需要返回完整的拆分集。我希望它们作为列而不是行返回

我尝试使用 split_part 和 unnest(字符串到数组)

sql postgresql split strsplit
1个回答
0
投票
create table test (id int,list varchar(50));
insert into test values
 (1,'Apple-Orange')
,(2,'Apple-Grapes-melon')
,(3,'Lemon')
,(4,'Lemon-Apple-Grapes-Melon-Orange-Other')
;
with words as(
select id,list,n,wrd
from test
cross join unnest(ARRAY[1,2,3,4]
   , STRING_TO_ARRAY(list,'-') )
as x(n,wrd) 
)
select id,min(list) list
  ,min(case when n=1 then wrd end) col1
  ,min(case when n=2 then wrd end) col2
  ,min(case when n=3 then wrd end) col3
  ,min(case when n=4 then wrd end) col4
  ,string_agg(case when n is null then wrd end, '-') colOther
from words
group by id

结果 |id|列表|col1|col2|col3|col4|colother| |-:|----:|----:|----:|----:|----:|----:| |3|柠檬|柠檬|空|空|空|空| |4|柠檬-苹果-葡萄-甜瓜-橙子-其他|柠檬|苹果|葡萄|瓜类|橙子-其他| |2|苹果-葡萄-瓜|苹果|葡萄|瓜|null|空| |1|苹果橙|苹果|橙|null|null|null|

© www.soinside.com 2019 - 2024. All rights reserved.