【发布时间】:2026-02-05 21:35:01
【问题描述】:
我一直在努力解决这个问题,尝试在这个论坛中找到解决方案,但我无法继续。我需要帮助。 我有一列存储船舶名称贯穿船舶的生命,我想将它们分成三列。 主要是我有这三个选项,
a) 只有一个名字
select t2.esp1,t2.espectro,t2.espectro1, t2.id from(
select substring(t.espectro, t.posfin)::varchar as esp1, t.espectro,t.espectro1,t.id from(
select "Id" as id, strpos(shipname, ', ') as posinic, strpos(shipname, ' y ') as posfin,shipname as espectro, shipname1 as espectro1 from ships) t)t2 (esp1, espectro, espectro1, id)
where t2.esp1 not like '% y %'`)
b) 两个名字
select t2.esp1,t2.espectro,t2.espectro1, t2.id from(
select substring(t.espectro,1, t.posfin)::varchar as esp1, t.espectro,t.espectro1,t.id from(
select "Id" as id, strpos(shipname, ', ') as posinic, strpos(shipname ' y ') as posfin,shipname as espectro, shipname1 as espectro1 from ships) t)t2 (esp1, espectro, espectro1, id)
where t2.esp1 not like '%, %'`) and for the second name (`select t2.esp1,t2.espectro,t2.espectro1, t2.id from(
select substring(t.espectro, t.posfin)::varchar as esp2, t.espectro,t.espectro2,t.id from(
select "Id" as id, strpos(shipname, ', ') as posinic, strpos(shipname, ' y ') as posfin,shipname as espectro, shipname2 as espectro2 from ships) t)t2 (esp2, espectro, espectro2, id)
where t2.esp2 like '% y %' and t2.espectro not like '%, %';
和c)三个名字:我可以得到第一个
select substring(t.espectro,1,t.posicion) from(
select strpos(shipname, ',') as posicion,shipname as espectro from ships) t;` and third `select t2.esp3,t2.espectro,t2.espectro3, t2.id from(
select substring(t.espectro, t.posfin)::varchar as esp3, t.espectro,t.espectro3,t.id from(
select "Id" as id, strpos(shipname, ', ') as posinic, strpos(shipname, ' y ') as posfin,shipname as espectro, shipname3 as espectro3 from ships) t)t2 (esp3, espectro, espectro3, id)
where t2.esp3 like '% y %' and t2.espectro like '%, %';
但不是第二个
三个命名记录如下所示:
Nuestra Señora del Rosario, Santo Domingo y San José
我已经尝试过这个选项:
select substring(t.shipsnames from '%#",_y#"%' for '#') as name2 from ships t
在#"pattern#" 中进行了几处更改,以查找空格并获取第二个名称。 然后我尝试了这个选项:
select t2.name2[6:7] from (regexp_split_to_array(t.shipnames, E'\\s+') as name2 from ships t) t2
但它不起作用,因为不是每条记录都具有相同的长度,因此有些记录像 {"Santo","Domingo"} 解决,而另一些则不像 {"Rosario",","}。 我不熟悉正则表达式 sintax,我在 PostgreSQL 文档中找到了这个示例。有什么提示吗?
【问题讨论】:
-
如果您需要同时使用空格和逗号进行拆分,请尝试
E'[\\s,]+'。 -
您到底想达到什么目标?当
Nuestra Señora del Rosario, Santo Domingo y San José被提供为输入时,您希望Nuestra Señora del Rosario、Santo Domingo和San José作为输出吗?如果是,一行三列还是三行一列?您能否提供 a) 和 b) 的解决方案作为示例? -
@markus-benko 我添加了代码来对我使用的记录进行子串化。它工作得很好。感谢您的反馈
-
我想在三个不同的列中获得三个名称,因为这三个名称是这艘船在其生命中获得的三个名称。因此,三列 name1、name2、name3 并将每个名称存储在那里。
标签: sql regex postgresql substring