使用数字字符对varchar数据类型进行排序

时间:2013-04-19 11:03:40

标签: sql-server-2008

我有一个varchar列,需要按照其中包含的数字进行排序。数据类似于:

Group 1
Group 10
Group 11
Group 12
Group 13
Group 14
Group 15
Group 16
Group 17
Group 18
Group 19
Group 2
Group 20
Group 3
Group 4
Group 5
Group 6
Group 7
Group 8
Group 9
Test Group

我想要输出这样的值,其中值按数字排序。

Group 1
Group 2
Group 3
Group 4
Group 5…..

1 个答案:

答案 0 :(得分:7)

如下所示,它会帮助你......

SELECT ColumnName FROM TableName 
ORDER BY CONVERT(INT, Replace(ColumnName, 'Group','')) 

SQL小提琴: http://sqlfiddle.com/#!3/e14a6/7

另一种方式

SELECT ColumnName FROM TableName 
ORDER BY LEN(ColumnName),ColumnName

SQL小提琴: http://sqlfiddle.com/#!3/e14a6/6

另一种方式

SELECT ColumnName FROM TableName order by 
case when 
    PATINDEX('%[^0-9]%',ColumnName) = 0 
THEN 
    data
ELSE
    cast(Left(ColumnName,PATINDEX('%[^0-9]%',ColumnName)-1) as int) 
END

SQL小提琴: http://sqlfiddle.com/#!3/14eb5/2

另一种方式

在这里,我使用Common Table Expression添加另一种解决方案试试这个......

with tempCTE(Data, pos)
as
(select data, Patindex('%[0-9]%', data)  from sample),
tempCTE2(name, num)
as
(select SUBSTRING(data, 0, pos) name , cast(SUBSTRING(data, pos , LEN(data)) as int) num from tempCTE)
select name + CAST(num as varchar(10)) num1 from tempCTE2 order by name, num asc

SQL小提琴: http://sqlfiddle.com/#!3/14eb5/3