比如:select * from talble where id in (1,2,4,8,3,6)
现在如果我需要结果就是IN中出现的顺序也就是:1,2,4,8,3,6
但是查询默认是按照in中的大小自动排序,就成了:1,3,4,6,8请问大家有什么好的简单办法能得到我需要的结果

解决方案 »

  1.   

    排序的三种方法1、case when
    2、charindex
    3、union all
      

  2.   

    --select * from talble where id in (1,2,4,8,3,6)
    --现在如果我需要结果就是IN中出现的顺序也就是:1,2,4,8,3,6
    --但是查询默认是按照in中的大小自动排序,就成了:1,3,4,6,8
    create table test
    (id int)
    insert test(id)
    select 3 union all
    select 1 union all
    select 8 union all
    select 1 union all
    select 2 union all
    select 4 union all
    select 3 union all
    select 4 union all
    select 8 union all
    select 3 union all
    select 6 --select * from testselect * 
    from test 
    where id in (1,2,4,8,3,6)
    order by 
    case id 
    when 1 then 1 
    when 2 then 2
    when 4 then 3
    when 8 then 4
    when 3 then 5 
    when 6 then 6 
    enddrop table test
      

  3.   

    select * from talble where id in (1,2,4,8,3,6) order by charindex(id,'1,2,4,8,3,6')