【问题标题】:Update series of numeric values in long string [closed]更新长字符串中的一系列数值[关闭]
【发布时间】:2020-09-16 13:18:00
【问题描述】:

我的文本列包含以下示例数据:

5,5,0.1;6,6,0.15;7,7,0.2;8,8,0.25;9,9,0.3;10,10,0.35;11,11,0.4;12,12,0.45;13,13,0.5;14,14,0.55;15,15,0.6;16,16,0.65;17,17,0.7;18,18,0.75;19,19,0.8;20,20,0.85;

我需要为每个数值添加一些固定值(分号之前的那个) 例如来自:

5,5,0.1;6,6,0.15;我想加 0.15 所以结果是:

5,5,0.25;6,6,0.3;

我想我应该尝试一下 regexp_replace 但我不知道如何从这里开始

【问题讨论】:

  • 这是一个糟糕的数据库设计。你有机会解决这个问题吗?使用适当的规范化模型,这将是一个非常简单的 UPDATE 语句

标签: regex string postgresql sql-update


【解决方案1】:

正确的解决方案是修复损坏的数据模型,而不是在单个列中存储多个分隔值。


我不会使用正则表达式来执行此操作,而是取消嵌套字符串的元素,将值添加到第三个元素,然后将所有内容聚合回损坏的设计:

update badly_designed_table
  set denormalized_column = 
       (select string_agg(concat_ws(',', a, b, round(c + 0.15,2)), ';' order by idx)
        from (
          select split_part(val, ',', 1) as a,
                 split_part(val, ',', 2) as b,
                 split_part(val, ',', 3)::numeric as c,
                 idx
          from unnest(string_to_array(bad_column, ';')) with ordinality as x(val,idx)
           -- skip the "empty" element generated by the trailing ;
          where nullif(val, '') is not null
        ) t) 

【讨论】:

  • 我知道这种结构很糟糕,但不幸的是我无法更改它,因为它是某些应用程序仍在使用的旧架构的一部分。但是您的查询非常完美,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 2020-01-03
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
相关资源
最近更新 更多