gpt4 book ai didi

postgresql - 以字符 SQL 拆分字符串

转载 作者:行者123 更新时间:2023-11-29 12:13:00 25 4
gpt4 key购买 nike

如何在 PostgreSQL 中将字符串拆分为字符并在每个字符后添加新行

例如

num  desc
1 Hello
2 Bye

num desc
1 H
e
l
l
o

2 B
y
e

最佳答案

select num, regexp_split_to_table(descr,'')
from the_table
order by num;

SQLFiddle:http://sqlfiddle.com/#!15/13c00/4

然而,字符的顺序无法保证,实现起来有点复杂。

基于 Erwin's answer regarding this problem :

select case 
when row_number() over (partition by id order by rn) = 1 then id
else null
end as id_display,
ch_arr[rn]
from (
select *,
generate_subscripts(ch_arr, 1) AS rn
from (
select id,
regexp_split_to_array(descr,'') as ch_arr
from data
) t1
) t2
order by id, rn;

编辑:

如果您只想为每个 id 指定一个字符串,其中字符由换行符分隔,您可以使用:

select id, 
array_to_string(regexp_split_to_array(descr,''), chr(10))
from data
order by id

关于postgresql - 以字符 SQL 拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22297463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com