【发布时间】:2020-08-16 21:00:05
【问题描述】:
我知道这是一个相对简单的问题,但我在使用 Google 的关键字时找不到任何内容。 我正在使用 SQL (Oracle) 引用具有类似数字的列:
- 100
- 12500
- 300
现在我需要删除最后 2 个零。 这种方法不起作用:
Trim(TRAILING '00' FROM F0035.Nr) "Sequence",
有人知道吗?
结果应该是带有数字的列,而不是文本
【问题讨论】:
我知道这是一个相对简单的问题,但我在使用 Google 的关键字时找不到任何内容。 我正在使用 SQL (Oracle) 引用具有类似数字的列:
现在我需要删除最后 2 个零。 这种方法不起作用:
Trim(TRAILING '00' FROM F0035.Nr) "Sequence",
有人知道吗?
结果应该是带有数字的列,而不是文本
【问题讨论】:
查看这两个选项:
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
【讨论】:
你可以这样做:
SELECT regexp_replace(F0035.Nr, '^(.*)00$', '\1')
FROM F0035
如果您的要求发生细微变化,您可以轻松调整正则表达式,例如删除超过 2 个尾随零(例如^(.*)00+)或其他字符
【讨论】:
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;
【讨论】:
如果列包含数字,为什么要使用字符串操作?
如果所有值都以两个00作为结尾,那么:
F0035.Nr / 100
如果有些没有,则使用case:
(case when mod(F0035.Nr, 100) = 0 then F0035.Nr / 100 else F0035.Nr end)
我不建议在大多数情况下转换为字符串来进行数字运算。
【讨论】:
where 或 on 子句中的此类结构几乎会扼杀优化器。另外,由于隐式转换错误,我浪费了大量时间调试查询(我的和其他人的)。
以下表达式将从数字中去除任意数量的零:
SELECT NR / POWER(10, LENGTH(REGEXP_SUBSTR(TO_CHAR(NR), '0*$')))
FROM F0035
【讨论】: