提取字符串的数字部分并获取列中的最大值

时间:2014-07-17 14:07:29

标签: mysql sql regex

我有一个表格foo,用lnnnnn格式存储代码,其中l至少有一个字母,n是数字值。字母或数字都可以有不同的长度,所以试图解决这个就像提到的here一样没有用。

示例:

 group | code
 =============
   1   | a0010
   1   | a0012
   1   | a0013
   2   | bn0014
   2   | bn0015
   2   | bn0016
   3   | u0017
   3   | u0018

我的任务是获取所需组中此列的当前最高数值,以生成新数字(如序列)。

请注意,我无法重新设计表并爆炸字符串和文本部分。

到目前为止,我试过了:

select 
    max(code rlike '[0-9]$')
from 
    foo
where
    group = 2

但遗憾的是,regexprlike(同义词)仅返回01(匹配或不匹配)。

3 个答案:

答案 0 :(得分:1)

一种方法是强力方法:

select grp,
       max(case when substr(code, 1, 1) between '0' and '9' then code + 0
                when substr(code, 2, 1) between '0' and '9' then substr(code, 2) + 0
                when substr(code, 3, 1) between '0' and '9' then substr(code, 3) + 0
                when substr(code, 4, 1) between '0' and '9' then substr(code, 4) + 0
                when substr(code, 5, 1) between '0' and '9' then substr(code, 5) + 0
                when substr(code, 6, 1) between '0' and '9' then substr(code, 6) + 0
                when substr(code, 7, 1) between '0' and '9' then substr(code, 7) + 0
                when substr(code, 8, 1) between '0' and '9' then substr(code, 8) + 0
           end)                
from foo
group by grp;

答案 1 :(得分:0)

如果所有数字部分都以0开头:

select gp, max(cast(substr(code, instr(code, '0')) as unsigned))
from t
group by gp

请参阅sqlfiddle

如果没有,对于任意数字部分(以任何数字开头):

select gp, max(cast(substr(code, instr(code, n)) as unsigned))
from t
join (select 0 n union select 1 union select 2 union select 3 union select 4 union select 5
     union select 6 union select 7 union select 8 union select 9) x
group by gp

请参阅sqlfiddle

答案 2 :(得分:0)

如果您的数字代码总是四位数,那么您可以这样做:

select groupid, max(right(code,4)) as maxcode
  from foo
 group by groupid

在这里查看小提琴:http://sqlfiddle.com/#!2/775b3/2