sql - 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 不是很出色,而且这个项目有很多。任何帮助都深表感谢。非常感谢
解决方案
一种方法是横向连接,它将阵列拉开,挑选出您想要的部分,然后重新聚合:
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。
推荐阅读
- ruby-on-rails - Ruby on Rails 插入错误 ***** PG::InsufficientPrivilege: 错误: 关系发票的权限被拒绝
- python - python使用“模板列表”创建新列表
- r - 如何从 0 开始计算观察的出现次数并将其存储在 R 中的新变量中?
- javascript - Javascript script-src 使页面加载两次?
- gams-math - GAMS - 矩阵行操作
- python - python sdk hyperledger 连接通过“无法连接到所有地址”
- dm-script - 调整 FIB/SEM 图像中的图像对比度 - 不影响图像底部的文本栏
- scikit-learn - sklearn 用许多参数编写我自己的预测器
- java - Java 添加新对象(H2 数据库)
- mongodb - MongoDB 相当于 Python 的 enumerate()