根据db2数据库中的数值,从字母数字字符串中查找最大值

时间:2017-01-17 09:02:58

标签: database db2

实际上我的栏目中有数据 - abc1,abc2,..,abc50,pqr1,pqr2,...,pqr120,xyz1,xyz2,...,xyz200。现在我想获得最大值为此目的使用前缀xyz.So的值我使用了这个查询--`

select MAX(fieldName) from table where fieldName like 'xyz%'

此查询返回结果为xyz99为max但预期结果应为xyz200为max ..现在我想知道如何在MAX函数中使用'like'查询来获得所需的输出。是否有任何方法可以找到基于其数值的最大值。

4 个答案:

答案 0 :(得分:1)

select * from table
where substring(fieldName,3,length(fieldName)-3) = 
(select max(substring(fieldName,3,length(fieldName)-3))  
from table)

答案 1 :(得分:0)

试试这个

SELECT max(CAST(substring(fieldName,4) AS UNSIGNED)) AS maxVal
FROM `table`
WHERE fieldName LIKE 'xyz%'

答案 2 :(得分:0)

使用SUBSTR() xxxnnn 值分隔为字符部分和整数部分。 Cast字符串的整数部分为整数。 Order by这两个部分分开 - 降序。使用FETCH FIRST选择最大值!

select fieldName
from table
where fieldName like 'xyz%'
order by substr(fieldName,1,3) desc,
         cast(substr(fieldName,4) as integer) desc
fetch first 1 row only

答案 3 :(得分:0)

尝试一下-

Select concat('XYZ', max(regexp_replace(fieldName, '[^0-9]', '', 'g') ::int)) from table;

如果您只想从字母数字字段中提取整数值,则可以简单地使用-

Select regexp_replace(fieldName, '[^0-9]', '', 'g') ::int) from table;