我有一张包含以下数据的表格
-------------
SOURCE_CD
-------------
100-CITIB001
100-CITIB002
100-CITIB003
100-COSMO001
100-COSMO002
100-COSMOSS3
我需要对最后三个字符进行子字符串并选择结果的最大数量。我使用以下查询:
SELECT MAX(SUBSTR(SOURCE_CD,10))
AS SOURCE_CD FROM SOURCE_TBL
WHERE SOURCE_CD LIKE '100-CITIB%';
这将返回'003',因为这是以'100-CITIB'开头的SOURCE_CD的最大值。同样对于'100-COSMO',结果将是'SS3'。但我需要修改此查询以检查最后三个字符是否为数字并获得最大数字。
在这种情况下,'100-COSMO'的结果应为'002',因为它是表格中的最大数字。
任何人都可以帮助修改查询以获得所需的结果吗?
答案 0 :(得分:0)
定义此函数
CREATE OR REPLACE function is_number(param varchar2) return NUMBER
as
ret number;
begin
ret := to_number(param);
return 1;
exception
when others then return 0;
end;
/
然后使用此查询;
SELECT MAX(SUBSTR(SOURCE_CD,10))
AS SOURCE_CD FROM SOURCE_TBL
WHERE SOURCE_CD LIKE '100-CITIB%'
and is_number(SUBSTR(SOURCE_CD,10))=1
答案 1 :(得分:0)
我添加了一个正则表达式,说该列的最后三个字符必须是数字。
with source_tbl as(
select '100-CITIB001' as source_cd from dual union all
select '100-CITIB002' as source_cd from dual union all
select '100-CITIB003' as source_cd from dual union all
select '100-COSMO001' as source_cd from dual union all
select '100-COSMO002' as source_cd from dual union all
select '100-COSMOSS3' as source_cd from dual
)
select max(substr(source_cd, -3)) -- Max of the last 3 characters
from source_tbl
where regexp_like(source_cd, '[[:digit:]]{3}$')