求先数字后字母的排序SQL语句
数据库某字段数据(22,11,1,2,2a,10,10a,10b,10c,12,15)我希望的排序结果是,从左边先取数字排序,然后再以剩下的字母排序,我想要的结果是:
1,2,2a,10,10a,10b,10c,11,12,15,22;我想要SQL语句代码,谢谢
个人的思路是,先对字段末尾字符时行判断,如果是字母,则将字母去掉后转为int型,若无字母,则直接转换为int型,然后对转换后的值进行排序。只是本人对SQL编程不懂,有木有大侠帮个忙。给高分啦。
[解决办法]
select * from tborder by cast(left(col,patindex('%[^0-9]%',col+',')-1) as int), col
[解决办法]
if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([col] varchar(3))insert [tb]select '22' union allselect '11' union allselect '1' union allselect '2' union allselect '2a' union allselect '10' union allselect '10a' union allselect '10b' union allselect '10c' union allselect '12' union allselect '15'goselect * from tborder by cast(left(col,patindex('%[^0-9]%',col+',')-1) as int), col/**col----122a1010a10b10c11121522(11 行受影响)**/
[解决办法]
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')BEGIN DROP TABLE tbaENDGOCREATE TABLE tba( col1 VARCHAR(100))GOINSERT INTO tbaSELECT '22' UNIONSELECT '11' UNIONSELECT '1' UNIONSELECT '2' UNIONSELECT '2a' UNIONSELECT '10' UNIONSELECT '10a' UNIONSELECT '10b' UNIONSELECT '10c' UNIONSELECT '12' UNIONSELECT '15'GOSELECT *FROM tbaORDER BY CASE PATindex('%[^1234567890]%',col1) WHEN 0 THEN CAST(col1 AS INT) ELSE CAST(LEFT(col1,PATindex('%[^1234567890]%',col1) - 1) AS INT) END, CASE PATindex('%[^1234567890]%',col1) WHEN 0 THEN '' ELSE RIGHT(col1,LEN(col1) - PATindex('%[^1234567890]%',col1) + 1) END col1122a1010a10b10c11121522
[解决办法]
/*create function [dbo].[fn_getnumber]( @mysql_one nvarchar(200))returns varchar(200)begin declare @mysql_two varchar(200) declare @sql_one int declare @sql_two int select @sql_one= patindex('%[0-9.]%',@mysql_one) select @sql_two= patindex('%[^0-9.]%', substring(@mysql_one,patindex('%[0-9.]%',@mysql_one),len(@mysql_one)-patindex('%[0-9.]%',@mysql_one)+1)) if @sql_two=0 begin select @mysql_two= substring (@mysql_one,@sql_one,len(@mysql_one)+1-@sql_one) end else begin select @mysql_two=substring (@mysql_one,@sql_one,@sql_two-1) end return @mysql_two;end*/declare @T table([col] varchar(3))insert @Tselect '22' union allselect '11' union allselect '1' union allselect '2' union allselect '2a' union allselect '10' union allselect '10a' union allselect '10b' union allselect '10c' union allselect '12' union allselect '15'select * from @T order by [dbo].[fn_getnumber](col)+0/*122a1010a10b10c11121522*/