首页 > 解决方案 > 在 PostgreSQL 11.0 中替换多个字符串的逗号分隔值中的字符串

问题描述

我在 PostgreSQL 11.0 中有下表

forms
ampoules, capsules, coated tablets, infusion ampoules, liquids, powders, tablets
capsules, coated tablets, powders, tablets, unspecified
coated tablets

我想为每一行替换此逗号分隔值中的某些字符串,并最终获得不同的值。例如。包衣片剂片剂,胶囊剂片剂,输液安瓿瓶。

所需的输出是:

forms_normalized
ampoules, liquids, powders, tablets
tablets, powders, unspecified
tablets

我没有解决这个问题的起点。非常感谢任何帮助。

谢谢

标签: stringpostgresqlreplace

解决方案


一种方法是将逗号分隔的列表扩展为“表”,然后将不同的值聚合回来并替换您想要的值。

select d.id, 
       (select string_agg(distinct case t.form
                             when 'coated tablets' then 'tablets'
                             when 'infusion ampoules' then 'ampoules'
                             else t.form
                           end, ',')
        from regexp_split_to_table(d.forms, '\s*,\s*') as t(form))
from data d

推荐阅读