Search code examples
sqlt-sqlnumericalphanumericsql-order-by

Numeric order by varchar


Hey guys I'm trying to sort my varchar column . I am almost done with it but I can't find the solution to make the following:

-999, -998, 0, 8A, 80, 80A, 90, A80, ADBA

At the moment it is (see code): -998, -999, 0, 8A, 80, 80A, 90, A80, ADBA

I only need to fix the negative values. Anyone got a solution for this problem?

 SELECT RANK_NUMBER FROM SHIPMENT_EVENT
    ORDER BY CASE WHEN ISNUMERIC(RANK_NUMBER) = 1 THEN RIGHT('0000000000' + RANK_NUMBER, 10) ELSE CASE 
                 WHEN LEFT(RANK_NUMBER, 1) LIKE '[0-9]' THEN RIGHT( 
                 '0000000000' 
                     + LEFT(SUBSTRING(RANK_NUMBER, PATINDEX('%[0-9.-]%', RANK_NUMBER 
                 ), 80 
                 ), 
                 PATINDEX 
                 ('%[^0-9.-]%', SUBSTRING(RANK_NUMBER, PATINDEX('%[0-9.-]%', 
                 RANK_NUMBER), 
                 80 
                 ) + 'X') -1), 10) 
                 ELSE RANK_NUMBER 
               END 
           END

Solution

  • I would expect something like:

    order by cast(left(col, patindex('%[^-0-9]%', col + 'x') - 1) as decimal(20, 0))