1. 程式人生 > >sqlserver資料庫對非有序性的欄位進行有序排列的解決方案

sqlserver資料庫對非有序性的欄位進行有序排列的解決方案

我有一個需求,需要使用者根據一個狀態status對查詢結果進行排序,該狀態為0,1,2,3,4
可是不同的角色要求不同的排序順序,比如角色1就需要{1,4,5,3,0,2},對於這種需求應該如何
寫sql呢。
答案:動態的在查詢結果檢視中新增一個新列,該列為temp_status,然後根據status來分別賦給
temp_status不同大小的值,然後通過temp_status進行排序。
如例子:

select applyid,num,numVal,productKind,status,creator,creatorName,applyDept,applyDeptName,createDate,auditDate,
case when obj.status!=3 then createDate end as nx_st_time,
case when obj.status=0 then obj.status
when obj.status=1 then obj.status
when obj.status=5 then (obj.status-3)
when obj.status=2 then (obj.status+1)
when obj.status=4 then obj.status
when obj.status=6 then (obj.status-1)
when obj.status=3 then (obj.status+3) end as temp_status,
case when obj.status=3 then createDate end as no_st_time
from hb_apply as obj where 1=1 and obj.creator=1274248068575
order by obj.temp_status, obj.status,obj.nx_st_time desc,obj.no_st_time desc