order by 奇特排序技巧

来源:互联网 发布:windows 触摸板 增强 编辑:程序博客网 时间:2024/04/20 14:27

網上看到了幾個 用order by 實現的特殊排序規則,感覺以後可能會用上,特記錄之,整理了一下,直接上代碼算了:

if object_id('tempdb..#temp') is not nulldrop table #tempcreate table #temp(col1 varchar(100), col2 varchar(100))insert into #tempselect '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排序-- 用 charindexselect col1,col2 from #temporder by charindex(col2,'4,1,2')-- order by 中用 caseselect col1,col2 from #temporder by case col2when '4' then 1when '1' then 2when '2' then 3else 3 + rand()end-- 用 unionselect col1,col2 from #temp where col2 = '4' union allselect col1,col2 from #temp where col2 = '1' union allselect col1,col2 from #temp where col2 = '2'------ 需求二、 col 4 排第一,其余随便select col1,col2 from #temporder by case col1when '4' then 1else 1 + rand()end------ 需求三、 随机排序select col1,col2 from #temporder by newid()