Is it possible to define a sort order for the returned results?
I would like the sort order to be 'orange' 'apple' 'strawberry' not ascending or descending.
I know ORDER BY can do ASC or DESC but is there a DEFINED('orange', 'apple', 'strawberry') type thing?
This will be running on SQL Server 2000.
The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause. For example: SELECT last_name FROM employees WHERE first_name = 'Sarah' ORDER BY last_name DESC; This SQL Server ORDER BY example would return all records sorted by the last_name field in descending order.
It's incredibly clunky, but you can use a CASE statement for ordering:
SELECT * FROM Blah ORDER BY CASE MyColumn WHEN 'orange' THEN 1 WHEN 'apple' THEN 2 WHEN 'strawberry' THEN 3 END
Alternately, you can create a secondary table which contains the sort field and a sort order.
TargetValue SortOrder orange 1 apple 2 strawberry 3
And join your table onto this new table.
Use a CASE statement:
ORDER BY CASE your_col WHEN 'orange' THEN 1 WHEN 'apple' THEN 2 WHEN 'strawberry' THEN 3 END
Alternate syntax, with an ELSE:
ORDER BY CASE WHEN your_col = 'orange' THEN 1 WHEN your_col = 'apple' THEN 2 WHEN your_col = 'strawberry' THEN 3 ELSE 4 END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With