Monday, 25 August 2014

Sort varchar datatype with numeric characters

I have a varchar column that needs to be sorted by the number included in it. The data is similar to:

Group 1
Group 10
Group 11
Group 12
Group 2
Group 20
Group 3
Group 4
Group 5
Group 6


Solution 1-

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


Solution 2-

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


Solution 3-

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

Solution 4-

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


Output:-

Group 1
Group 2
Group 3
Group 4
Group 5
Group 6
Group 10
Group 11
Group 12
Group 20


if u have the series like this:-

1
B
A
10
B1
2

and you need Output like this :-

1
2
10
A
B
B1

use below query-

Solution 1-

select MyColumn
from MyTable
order by
 case IsNumeric(MyColumn)
        when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
        else MyColumn
   end 




Reference url-



No comments:

Post a Comment