一种受限的SQL分组排序土办法

要求对表数据进行排序,表字段中,有国,省,市,县,镇五个字典,外加一个sort字段。排序规则如下:
国-sort-省-sort-市-sort-县-sort-镇-sort

涉及到一个分组排序问题,然后数据又是一个整体。挺棘手的,想了如下受限的办法排:

select xxx from xxx where xxx order by 
case
	when nation_id    is not null and nation_id!=''    then  sort+5000000000
	when province_id  is not null and province_id!=''  then  sort+4000000000
	when city_id      is not null and city_id!=''      then  sort+3000000000
	when county_id    is not null and county_id!=''    then  sort+2000000000
	when town_id      is not null and town_id!=''      then  sort+1000000000
else 0 end DESC;

原理:
强制将sort分成了国,省,市,县,镇5个区间。然后取区间数值排序即可。勉强满足了业务需求。
最终排序的数字是:
国:5000000000-599999999999
省:4000000000-499999999999
市:3000000000-399999999999
县:2000000000-299999999999
镇:1000000000-199999999999
对结果数据排序,就满足了国-sort-省-sort-市-sort-县-sort-镇-sort的要求。

有如下限制:
sort不能超过1000000000,超过了就跨区间了。这点可以从页面限制填写的序号大小即可。
只能倒序,默认序号为0,空值排到最后面

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值