views:

80

answers:

1
+1  Q: 

Order BY in SQL

In my SQL statement, need to parse a title field so I can order by the integers. Basically, just extract the integers into a new field and order on that field.

the data in the title field looks like the following (WRONG):

TT TEST 750-1
TT TEST 80-1
TT TEST 1 UU 25-1
TT TEST 1 UU 420-1
TT TEST 1 UU 55-46
TT TEST 1 UU 600-8-10
TT TEST 1 UU 608-20
TT TEST 1 UU 750-1

after order by (CORRECT)

TT TEST 80-1
TT TEST 750-1
TT TEST 1 UU 25-1
TT TEST 1 UU 55-46
TT TEST 1 UU 420-1
TT TEST 1 UU 600-8-10
TT TEST 1 UU 608-20
TT TEST 1 UU 750-1

Thanks.

+2  A: 

You could use the PATINDEX function:

SELECT 
    CAST(SubString(REPLACE(Title,'-',''),
    PATINDEX('%[0-9]%',REPLACE(Title,'-','')),
    Len(REPLACE(Title,'-',''))) 
    AS INT)
AS [Title Number],*
FROM [Your table-name here] 
ORDER BY [Title Number]

Edit: Will work with hyphen now.

Note: Will not work if the Non-numeric part of the title has numbers or has a hyphen ('-').

Raze2dust
The solution you gave is just a little off...here's the sort it produced: <pre> (1)TT TEST 1 UU 25-1 (2)TT TEST 1 UU 420-1 (3)TT TEST 1 UU 55-46 (4)TT TEST 1 UU 600-8-10 (5)TT TEST 1 UU 608-20 (6)TT TEST 1 UU 750-1 (7)TT TEST 750-1 (8)TT TEST 80-1 <code>
gates
I'd say you probably have the information to fix it now gates.
Toby Allen
Yup, as I said, if the non-index part has numbers (Like 1 in your case), then it won't work. You can try inverting the Title (Use REVERSE()), extracting the numeric index, then invert back the index and cast it to INT and then sort. Let me know if you were able to do it that way..
Raze2dust
Probably make a stored proc and use temporary tables to do this so that the script looks less messy..
Raze2dust
Even better, Invert the Title. ('TT TEST 1 UU 25-1' becomes '1-52 UU 1 TSET TT'), get the substring upto the first space (i.e, '1-52'), replace the hyphen('-') with empty char ('') (becomes '152'), invert back the string (becomes '251') and cast this as [Title number] (INT)) and sort..
Raze2dust