首页 > 解决方案 > SQL 用元素前缀替换字符串列表

问题描述

在 Postgres 中,我有一个表格,其中有一列是文本列表:

devdb=> \d txyz
               Table "public.txyz"
    Column     |  Type  | Collation | Nullable | Default
---------------+--------+-----------+----------+---------
 status        | text   |           |          |
 lstcol        | text[] |           |          |

lstcol包含

devdb=> select lstcol from txyz limit 1 ;
                                 lstcol
----------------------------------------------------------------------
 {"ABCD - Company One Ltd","EFG - Second Corp."}

我想用 , 之前的单词替换列表中包含的每个" - "元素

 {"ABCD","EFG"}

我怎样才能做到这一点?可以创建另一列,然后替换原来的列。

我的 SQL 不是很出色,而且这个项目有很多。任何帮助都深表感谢。非常感谢

标签: sqlpostgresql

解决方案


一种方法是横向连接,它将阵列拉开,挑选出您想要的部分,然后重新聚合:

select t.*, x.ar
from txyz t cross join lateral
     (select array_agg(split_part(col, ' - ', 1)) as ar
      from unnest(t.lstcol) col
     ) x;

是一个 db<>fiddle。


推荐阅读