postgresql 在postgres中的n个字符后插入点

uinbv5nw  于 12个月前  发布在  PostgreSQL
关注(0)|答案(2)|浏览(98)

我在postgres中有以下表格

col1 
A018
B672

我想在前两个字符上加一个点。预期输出为:

col1   col2
A018   A01.8
B672   B67.2

到目前为止,我已经尝试了下面的查询

with missed_codes as (
SELECT col1, regexp_replace(col1, '(.{2})(?!$)', '\1.') as col2 FROM table 
)
select * from missed_codes ;

我得到这个输出

col1   col2
A018   1.18
B672   1.72

任何帮助是高度赞赏!

xn1cxnb4

xn1cxnb41#

对于示例数据,您不需要regex,只需leftsubstr

with missed_codes as (
  SELECT col1, substr(col1, 1, 3) || '.' || substr(col1, 4) as col2 FROM "table"
)
select * from missed_codes

输出量:

col1    col2
A018    A01.8
B672    B67.2

dbfiddle.uk上的演示

l7mqbcuq

l7mqbcuq2#

如果我理解正确,您需要在前两位数字后添加一个点,在这种情况下,您需要使用regexp_replace

SELECT col1, regexp_replace(col1, '^(\D*\d{2})(?!$)', '\1.') as col2 
FROM "table"

Demo here

相关问题