【问题标题】:TRIM Trailing Zeros修剪尾随零
【发布时间】:2020-08-16 21:00:05
【问题描述】:

我知道这是一个相对简单的问题,但我在使用 Google 的关键字时找不到任何内容。 我正在使用 SQL (Oracle) 引用具有类似数字的列:

  • 100
  • 12500
  • 300

现在我需要删除最后 2 个零。 这种方法不起作用:

Trim(TRAILING '00' FROM F0035.Nr)         "Sequence", 

有人知道吗?

结果应该是带有数字的列,而不是文本

【问题讨论】:

    标签: sql oracle trim


    【解决方案1】:

    查看这两个选项:

    SQL> with test (col) as
      2    (select '100'   from dual union all
      3     select '12500' from dual union all
      4     select '300'   from dual
      5    )
      6  select col,
      7    to_number(substr(col, 1, length(col) - 2)) result_1,
      8    to_number(col) / 100 result_2
      9  from test;
    
    COL     RESULT_1   RESULT_2
    ----- ---------- ----------
    100            1          1
    12500        125        125
    300            3          3
    
    SQL>
    
    • 第一个删除最后两个字符(从您的示例数据中,它们似乎总是00
    • 第二个将“数字”除以100

    【讨论】:

    • 谢谢!第一个完美运行。 100 的偏差不适用于 150 之类的值。这表示的不是整数。
    【解决方案2】:

    你可以这样做:

    SELECT regexp_replace(F0035.Nr, '^(.*)00$', '\1')
    FROM F0035
    

    如果您的要求发生细微变化,您可以轻松调整正则表达式,例如删除超过 2 个尾随零(例如^(.*)00+)或其他字符

    【讨论】:

      【解决方案3】:
      with test (col) as (
        select 10   from dual union all
        select 100  from dual union all
        select 1000 from dual union all
        select 12500 from dual union all
        select 125002 from dual union all
        select 3000   from dual
      )
      select col, 
      case when substr(col, -2) = '00' then col/100 else col end newnum
      from test;
      

      【讨论】:

        【解决方案4】:

        如果列包含数字,为什么要使用字符串操作?

        如果所有值都以两个00作为结尾,那么:

        F0035.Nr / 100
        

        如果有些没有,则使用case

        (case when mod(F0035.Nr, 100) = 0 then F0035.Nr / 100 else F0035.Nr end)
        

        我不建议在大多数情况下转换为字符串来进行数字运算。

        【讨论】:

        • 感谢您的建议。为什么不建议对字符串进行数值运算?
        • @joshua 。 . . SQL 有类型是有原因的。字符串和数字是不同的野兽。此外,whereon 子句中的此类结构几乎会扼杀优化器。另外,由于隐式转换错误,我浪费了大量时间调试查询(我的和其他人的)。
        【解决方案5】:

        以下表达式将从数字中去除任意数量的零:

        SELECT NR / POWER(10, LENGTH(REGEXP_SUBSTR(TO_CHAR(NR), '0*$')))
          FROM F0035
        

        db<>fiddle here

        【讨论】:

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