【问题标题】:Postgresql - How to get numeric value from the end of string and string without end numeric valuePostgresql - 如何从字符串的末尾和没有结束数值的字符串中获取数值
【发布时间】:2019-11-29 17:02:53
【问题描述】:

我在 Postgresql 用户表中有以下用户名。

**username**
test
123test
123test456
test123
test45test
test55test55

所以我试图分别获取没有结束数值和结束数值的字符串。

我期待以下输出

str          num
----------------
test         0
123test      0
123test      456
test         123
test45test   0
test55test   55

如何编写返回上述结果的 Postgresql 查询?

【问题讨论】:

    标签: regex string postgresql trim numeric


    【解决方案1】:

    您可以使用regexp_replace()substring()

    select
        regexp_replace(username, '\d+$', '') str,
        coalesce(substring(username from '\d+$')::int, 0) num
    from mytable
    

    Demo on DB Fiddlde

    with mytable as (
        select 'test' username
        union all select '123test'
        union all select '123test456'
        union all select 'test123'
        union all select 'test45test'
        union all select 'test55test55'
    )
    select
        regexp_replace(username, '\d+$', '') str,
        coalesce(substring(username from '\d+$')::int, 0) num
    from mytable
    
    字符串 |数 :--------- | --: 测试 | 0 123测试 | 0 123测试 | 456 测试 | 123 测试45测试 | 0 测试55测试 | 55

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多