Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by only the numeric part of a string

I have a column called Number populated with this data (column is nchar):

1
2
1091
3
20
2B

I want a select statement that give this order:

1
2
2B
3
20
1091

How I can accomplish this? Thanks everybody for your help

(EDITED)

like image 428
BernieSF Avatar asked Sep 21 '12 20:09

BernieSF


1 Answers

You can perform some tricks by converting to a numeric after you discover the location of the first non-numeric. Appending a random character at the end makes it treat all strings the same even if the original string did not contain an alphabetic.

SELECT [Number] FROM dbo.TableName 
ORDER BY CONVERT(INT, LEFT(Number, PATINDEX('%[^0-9]%', Number + 'z')-1));
like image 173
Aaron Bertrand Avatar answered Sep 19 '22 17:09

Aaron Bertrand