1

我有一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…..
4

1 回答 1

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

另一种方式

在这里,我使用公用表表达式添加了另一个解决方案试试这个......

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

于 2013-04-19T11:13:15.920 回答