您的位置:首页 > 数据库

SQL语句 - 使用order by优先级排序

2015-12-03 13:56 387 查看
背景:现有地区表area_info,地区表只有一个字段admincode,表示地区编号,要求查询所有地区编号出来,其中“1305”开头的编号排在首位,“1307”开头的编号排在第二位。



使用SQL语句的order by 和case when进行优先级排序:

select * from area_info where admincode like '13%'
order by
case when admincode like '1305%' then 1 else 10 end,
case when admincode like '1307%' then 2 else 10 end;




其中“1”和“2”所在位置的内容只是组别,不超过10不影响排序。对比结果如下:





如果还想进行二级排序,令每一个组合里(这里1305为一个组合)升序排序:
select * from area_info where admincode like '13%'
order by
case when admincode like '1305%' then 5 else 10 end,
case when admincode like '1307%' then 2 else 10 end,
admincode;


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: