Just sort by LENGTH of field and then for values with equal length:
SELECT myfield from mytable order by
LENGTH(myfield) DESC,
myfield DESC
Question
I have example data
SMMP022011304196
SMMP022011304199
SMMP022011304197
SMMP022011304193
SMMP022011304195
SMMP022011304198
SMMP022011304192
SMMP0220113041910
SMMP022011304191
SMMP022011304194
If I use SELECT myfield from mytable order by myfield DESC
I got result like this
SMMP022011304199
SMMP022011304198
SMMP022011304197
SMMP022011304196
SMMP022011304195
SMMP022011304194
SMMP022011304193
SMMP022011304192
SMMP0220113041910
SMMP022011304191
Please help to make result like this :
SMMP0220113041910
SMMP022011304199
SMMP022011304198
SMMP022011304197
SMMP022011304196
SMMP022011304195
SMMP022011304194
SMMP022011304193
SMMP022011304192
SMMP022011304191
Solution
Just sort by LENGTH of field and then for values with equal length:
SELECT myfield from mytable order by
LENGTH(myfield) DESC,
myfield DESC
OTHER TIPS
If the data always have SMMP in front, you could use below:
ORDER BY LPAD(REPLACE(myfield,'SMMP',''),15,'0') desc;
The logic for this method is to ignore the 4 char in front and only sort the numeric figure behind.
Following my earlier comment, sort as follows:-
SELECT myfield
FROM mytable
ORDER BY SUBSTRING(myfield, 1, 4) DESC, cast(SUBSTRING(myfield, 5) AS unsigned) DESC
Note this only works if your field is of a fixed format with 4 characters followed by numerics
This is working fine. Below code is work for SQL Server 2008 R2 :
SELECT
myfield
FROM mytable
ORDER BY
LEN(myfield) DESC
,myfield DESC