SQL自定义排序
前一阵子有一个需求,要按照用户的需求安排排序规则:
举例:
用户要求table_example中的数据按照class字段值C、A、D、B的顺序排序。
方法一:
开始想了一个方法是select的时候增加一个自定义字段custom,当class的值为C、A、D、B时令custom的值为1、2、3、4.
利用case when时,发现无需增加自定义字段即可实现:
select * from teble_exaple order by
(
case class
when 'C' then 1,
when 'A' then 2,
when 'D' then 3,
when 'B' then 4
else '' end
)
方法二:
利用程序端控制,由于用的PB,实现起来逻辑还是比较复杂,没有深究,思路:(仅为参考,未实现.)
dw_1.setsort(if(class = 'A', 'C', if(class = 'B', 'D', class)) A)
dw_1.sort
方法三:
利用decode函数:
select * from table_example order by decode(class,'C',1,'A',2,'D',3,'B',4)
sqlserver中类似功能的函数为charindex.
方法三为最简洁的方案,个人感觉很多情况下能用sql实现的功能比程序端实现要直接。