-
How to ORDER BY designated list of key values
I need to be able to order the results of a SELECT query by the order of a specific list of key IDs provided in the WHERE IN statement.
So my query looks like:
SELECT *
FROM TableName
WHERE KeyID IN (3,104,43,22,345)
ORDER BY ????
I need the results returned in the order provided in the IN list (3,104,43,22,345).
Thanks in advance!
pr0
-
You can only order by column, not values of the column. Try use union to put them together in your designated order.
-
how's that?
I'm not quite sure how to use UNION for that purpose. Could you elaborate? Thanks!
-
Code:
SELECT *
FROM TableName
WHERE KeyID IN (3,104,43,22,345)
ORDER BY
Case KeyID
WHEN 3 Then 1
WHEN 104 Then 2
WHEN 43 Then 3
WHEN 22 Then 4
WHEN 345 Then 5
End
-
It worked!
Thanks russellb! That was the perfect solution. I never would have figured that one out.
pr0
-
glad 2 help. the other way, which i think rm was going after is this
Code:
select *, 1 as sortVal from table where KeyID = 3
UNION
select *, 2 as sortVal from table where KeyID = 104
UNION
select *, 3 as sortVal from table where KeyID = 43
...
ORDER BY sortVal
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|