最近在做项目中一直用到case when,在各种场景下都能用到,真的感觉是好强大,贼牛逼,废话不多说,直接上实例
一.多条件排序
项目中有这么一个需求,标签列表展示,按照已领用的普通卡排第一位,已领用的临时卡排第二位,未领用的普通卡排第三位,未领用的临时卡排第四位,禁用的普通卡排第五位,禁用的临时卡排第六位,普通卡临时卡字段是type(0:普通卡,1:临时卡),领用字段是card_status(标签状态(0:启用(已领用),1:未领用,2:禁用),下面是sql
select * from newcloud_access_card order by
case
when card_status='0' and type ='1' then 0
when card_status='0' and type ='0' then 1
when card_status='1' and type ='1' then 2
when card_status='1' and type ='0' then 3
when card_status='2' and type ='1' then 4
when card_status='2' and type ='0' then 5
end;
按照上面这种写法无论多么复杂的排序都可以实现