order by 特殊排序技巧

if object_id('tempdb..#temp') is not null  
    drop table #temp  
  
create table #temp(col1 varchar(100), col2 varchar(100))  
insert into #temp  
select 'X68.23','4'  
union all select 'X86.32','2'  
union all select 'ZA11.30','1'  
union all select 'ZB11.47','1'  
go  
  
------ 需求一、按col 4,1,2排序  
-- 用 charindex  
select col1,col2 from #temp  
order by charindex(col2,'4,1,2')  
  
-- order by 中用 case  
select col1,col2 from #temp  
order by   
    case col2  
        when '4' then 1  
        when '1' then 2  
        when '2' then 3  
        else 3 + rand()  
    end  
  
-- 用 union  
select col1,col2 from #temp where col2 = '4' union all  
select col1,col2 from #temp where col2 = '1' union all  
select col1,col2 from #temp where col2 = '2'  
  
------ 需求二、 col 4 排第一,其余随便  
select col1,col2 from #temp  
order by   
    case col1  
        when '4' then 1  
        else 1 + rand()  
    end  
  
------ 需求三、 随机排序  
select col1,col2 from #temp  
order by newid()  
  1. if object_id('tempdb..#temp'is not null  
  2.     drop table #temp  
  3.   
  4. create table #temp(col1 varchar(100), col2 varchar(100))  
  5. insert into #temp  
  6. select 'X68.23','4'  
  7. union all select 'X86.32','2'  
  8. union all select 'ZA11.30','1'  
  9. union all select 'ZB11.47','1'  
  10. go  
  11.   
  12. ------ 需求一、按col 4,1,2排序  
  13. -- 用 charindex  
  14. select col1,col2 from #temp  
  15. order by charindex(col2,'4,1,2')  
  16.   
  17. -- order by 中用 case  
  18. select col1,col2 from #temp  
  19. order by   
  20.     case col2  
  21.         when '4' then 1  
  22.         when '1' then 2  
  23.         when '2' then 3  
  24.         else 3 + rand()  
  25.     end  
  26.   
  27. -- 用 union  
  28. select col1,col2 from #temp where col2 = '4' union all  
  29. select col1,col2 from #temp where col2 = '1' union all  
  30. select col1,col2 from #temp where col2 = '2'  
  31.   
  32. ------ 需求二、 col 4 排第一,其余随便  
  33. select col1,col2 from #temp  
  34. order by   
  35.     case col1  
  36.         when '4' then 1  
  37.         else 1 + rand()  
  38.     end  
  39.   
  40. ------ 需求三、 随机排序  
  41. select col1,col2 from #temp  
  42. order by newid()  
  43. ORDER BY
    case when state=5 then 2 else 1 end ASC,
    weight_op_time DESC

原文地址:https://www.cnblogs.com/cosyer/p/6530197.html