SQL : sorting based on IN parameters

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • waqasahmd
    New Member
    • Nov 2009
    • 13

    SQL : sorting based on IN parameters

    I have a following query.

    Code:
    select HeaderFieldName from TMS_Header where ID IN (1,2,3,15,10,8)
    but the problem is that i get result sorted on base of Primary Key[whic is by default behaviour]. Instaed i need results [HeaderFieldName] sorted on basis of (1,2,3,15,10,8) which i am giving input.

    Kindly suggest alteraton in the query
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    This is a strange ORDER BY demand.
    It may be simple but I can't see it.
    But it is possible by creating a temp table like
    Code:
    id value
    1   1
    2   2
    3   3
    4   15
    5   10
    6   8
    Then JOIN ON value and order by id.

    Comment

    • waqasahmd
      New Member
      • Nov 2009
      • 13

      #3
      thanks for the solution

      Actually, i have this solution to that problem once in my life but now i forget it.

      as requirement I just want my data in the order in which i provide IDs in the 'IN' parameters

      Comment

      • gpl
        New Member
        • Jul 2007
        • 152

        #4
        Try
        Code:
        SELECT Headerfieldname 
        FROM   Tms_header 
        WHERE  Id IN ( 1, 2, 3, 15, 10, 8 ) 
        ORDER  BY CASE Id 
                    WHEN 1 THEN 1 
                    WHEN 2 THEN 2 
                    WHEN 3 THEN 3 
                    WHEN 15 THEN 4 
                    WHEN 10 THEN 5 
                    WHEN 8 THEN 6 
                  END

        Comment

        Working...