【问题标题】:Postgresql replace comma from right in position 3 and replace dot and comma left to that positionPostgresql 在位置 3 中从右侧替换逗号并将点和逗号从左侧替换到该位置
【发布时间】:2021-03-03 15:20:51
【问题描述】:

我的货币价值带有逗号和点。我需要将一些欧洲风格的货币更改为英国风格的值。

11,200.00 -> 11200.00
11.200,00 -> 11200.00
58.20 -> 58.20
58,20 -> 58.20
2500 -> 2500

我尝试过使用 right() 和替换函数,但没有成功。

谁能帮我写一个替换函数来处理这个问题。

【问题讨论】:

  • 为什么将数字存储在text(或varchar)列中?这是一个真的,非常糟糕的主意。在继续之前,您有机会修复这个损坏的设计吗?
  • 该设计类似于按行键值对,每个键是不同的数据类型,存储为字符串
  • 已经上线了。现在我们遇到进来的欧式货币价值。
  • 这样的设计不应该投入生产。
  • 问题是关于解析传入数据而不是存储,对吧?

标签: sql postgresql replace


【解决方案1】:

这是欧洲国家的一个问题,尤其是当新旧软件必须共存时。 如果从外部来源“传入欧洲风格的货币价值”,那么您别无选择,只能处理它们。首先尝试通过正则表达式匹配确定字符串值属于哪种样式,然后进行相关修正。像这样的插图:

select case 
 when :strval ~ '^[+-]?(\d+\.)*\d+(,\d+)$' then replace(replace(:strval, '.', ''), ',', '.')
 when :strval ~ '^[+-]?(\d+,)*\d+(\.\d+)$' then replace(:strval, ',', '')
 when :strval ~ '^[+-]?\d+$' then :strval
 -- maybe there are other formats so the list may grow
end; 

作为一个函数:

create or replace function unify_numeric_format(strval text)
returns numeric language sql immutable as
$$
select case 
 when strval ~ '^[+-]?(\d+\.)*\d+(,\d+)$' then replace(replace(strval, '.', ''), ',', '.')
 when strval ~ '^[+-]?(\d+,)*\d+(\.\d+)$' then replace(strval, ',', '')
 when strval ~ '^[+-]?\d+$' then strval
 -- maybe there are other formats so the list may grow
end::numeric; 
$$;

【讨论】:

  • 这与“欧洲风格的货币”无关 - 这是任何应该在国际环境中使用的软件都需要考虑的问题 - 不仅适用于货币,而且对于日期和时间值。该问题的唯一正确解决方案是从不存储格式化值,而是使用正确的数据类型,numeric 用于数字,date 用于日期,timestamp用于日期/时间值等。然后可以在显示为用户想要的任何格式时对其进行格式化
  • 我完全同意。内容与呈现分离。不幸的是,存在确实存储格式化值的现有系统。这是生活中的事实。有时这些非常昂贵或对业务至关重要,因此他们必须与合适的人交谈才能以某种方式融入新环境。
【解决方案2】:

为了解决这个具体问题,我会做两个replace() 步骤:

demo:db<>fiddle

SELECT replace(replace('11.200,00', '.', ''), ',', '.')

尽管如此,您应该认真对待@a_horse_with_no_name 的评论:不要将值存储为类型text。

编辑:等等,你有两个变体:11.200,00 AND 11,200.00 ?您必须规范化此表。请将列类型切换为numeric。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多