日期:2014-05-18 浏览次数:20778 次
表中有这么个字段 Name ----------------------------- aa aa[1] aa[2] aa(1) bb cc cc[1] 我想 要的效果 aa 4 bb 1 cc 2
if object_id('[tb]') is not null drop table [tb] go create table [tb]([Name] varchar(5)) insert [tb] select 'aa' union all select 'aa[1]' union all select 'aa[2]' union all select 'aa(1)' union all select 'bb' union all select 'cc' union all select 'cc[1]' go select left(name,charindex('[',replace(name,'(','[')+'[')-1) as name,count(1) as cnt from tb group by left(name,charindex('[',replace(name,'(','[')+'[')-1) /** name cnt ----- ----------- aa 4 bb 1 cc 2 (3 行受影响) **/
------解决方案--------------------
go create table #s( col varchar(10) ) insert #s select 'B3' union all select 'C1' union all select 'D\4' union all select '4MD' union all select 'AR/12BD' ;with t as( select substring(col+' ',patindex( '%[0-9]% ',col+' '),len(col+' ')) as col1 from #s ) select left(col1+' ',patindex( '%[^0-9]% ',col1+' ')-1) as col from t /* col 3 1 4 12 4 */ 如果是无规则字符串中的截取数字请参考以上方法