0

I have lots of keywords - "b1,b2,b3,a1,z1" which later would be composed as a query condition to do a query from a database.

It's like this:

SELECT * 
  FROM sometable
 WHERE id IN (b1,b2,b3,a1,z1)

But the search results are a mess in order.

    ID
------------   
    a1
    b2
    b3
    b1
    z1

The question is how to make the search results are presented perfectly as b1,b2,b3,a1,z1

chancrovsky
  • 582
  • 3
  • 11
ske
  • 4,694
  • 3
  • 23
  • 35

2 Answers2

1

One method is to use charindex():

ORDER BY CHARINDEX(',' + CAST(id AS VARCHAR(255)) + ',', ',b1,b2,b3,a1,z1,')

Another method is to use join:

SELECT s.*
FROM sometable s JOIN
     (VALUES ('b1', 1), ('b2', 2), ('b3', 3), ('a1', 4), ('z1', 5)
     ) v(id, priority)
     ON s.id = v.id
ORDER BY v.priority;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

If ID is always a character plus a single digit number you can use this. You need to adjust the numbers if they can contain more than 1 character or more than 1 digit numbers.

SELECT *
FROM sometable
ORDER BY SUBSTRING(ID, 1, 1)
, SUBSTRING(ID, 2, 1)
chancrovsky
  • 582
  • 3
  • 11
artm
  • 8,554
  • 3
  • 26
  • 43