select * from Article where id in(6,3,4,2,7,1,5)
这条语句输出的记录集排序是按id=1、2、3、4、5、6、7 来排序的,但是我现在要求是要它输出记录时按6,3,4,2,7,1,5的排序输出,咱办啊?

解决方案 »

  1.   

    select * from Article where id in(6,3,4,2,7,1,5)
    order by charindex(','+ltrim(id),+',',',6,3,4,2,7,1,5,')
      

  2.   

    select * from Article where id in(6,3,4,2,7,1,5)
    order by (case when id=6 then 1 
                   when id=3 then 2
                   when id=4 then 3
                   when id=2 then 4
                   when id=7 then 5
                   when id=1 then 6
                   when id=5 then 7
               else 8);
      

  3.   

    要报错啊
    函数 charindex 的参数 3 的数据类型 varchar 无效。
      

  4.   

    declare @a varchar(20)
    set @a='6,3,4,2,7,1,5'
    exec('select * from master..spt_values where number in ( '+ @a +' )
    and type=''p''
    order by charindex('',''+ltrim(number)+'','','','+@a+','')')
    /*
    name                                number      type low         high        status
    ----------------------------------- ----------- ---- ----------- ----------- -----------
    NULL                                6           P    1           64          0
    NULL                                3           P    1           8           0
    NULL                                4           P    1           16          0
    NULL                                2           P    1           4           0
    NULL                                7           P    1           128         0
    NULL                                1           P    1           2           0
    NULL                                5           P    1           32          0(7 行受影响)
    */
      

  5.   

    declare @a varchar(20)
    set @a='6,3,4,2,7,1,5'
    print 'select * from master..spt_values where number in ( '+ @a +' )
    and type=''p''
    order by charindex('',''+ltrim(number)+'','','','+@a+','')'
    /*
    select * from master..spt_values where number in ( 6,3,4,2,7,1,5 )
    and type='p'
    order by charindex(','+ltrim(number)+',',',6,3,4,2,7,1,5,')*/
      

  6.   

    --try
    select * from Article where id in (6,3,4,2,7,1,5)
    order by charindex(','+ltrim(cast(id as varchar(2))),',',',6,3,4,2,7,1,5,')