【问题标题】:Extract number before and after character提取字符前后的数字
【发布时间】:2021-01-05 12:33:26
【问题描述】:

我需要从 sql 中的“输入”列中的“TblA”中提取某个数字。 我有以下示例输入和所需的输出 1 和 2。

Input Desired Output 1 Desired Output 2
20 x 88 nc. 20 88
100 x 300 nc 100 300
200x 88 nc. 200 88
5x 300 nc 5 300
ol (200x 88nc.) 200 88
ol (100x 300nc) 100 300
90dfa (45x65) 45 65
90dfa (45 x 65) 45 65
5,5 x 30 nc 5,5 30
5.5 x 30 nc 5.5 30

您能帮我处理这段代码吗? 先感谢您。 我过去曾使用过第 N 个字符的左右函数。 但我不知道从哪里开始这段代码。 我正在使用 sql server 2019

【问题讨论】:

  • “我尝试使用字符串替换,但这不起作用。” 那是什么尝试?您忘记将其包含在您的问题中。向我们展示该尝试,以便我们了解它为什么不起作用。

标签: sql sql-server sql-server-2019


【解决方案1】:

假设您的字符串中只有一个 'x'(如所有示例中一样),那么以下工作:

select *
from t cross apply
     (select stuff(col1, 1, len(col1) - patindex('%[^0-9,.]%', reverse(col1) + ' ') + 1, '') as col1,
             left(col2, patindex('%[^0-9,.]%', col2 + ' ') - 1) as col2
      from (values (replace(left(t.input, charindex('x', t.input) - 1), ' ', ''),
                    replace(stuff(t.input, 1, charindex('x', t.input), ''), ' ', '')
                   ) 
           ) v(col1, col2)
     ) v;

Here 是一个 dbfiddle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 2016-04-04
    • 2015-06-06
    • 1970-01-01
    相关资源
    最近更新 更多