数据库查询,某状态的数据放在最前面,其他的排在后面

您所在的位置:网站首页 dbf排序倒序 数据库查询,某状态的数据放在最前面,其他的排在后面

数据库查询,某状态的数据放在最前面,其他的排在后面

2024-01-20 00:34| 来源: 网络整理| 查看: 265

需求

事务预约系统,数据有多个状态,包括"待处理"、“已完成”、“终止”、“退回”、“撤回”,对应的状态码status分别是:0、1、2、3、4; 在查询列表中,将 “待处理” 任务排在前面,按照预约时间appoint_time正序排序,其他状态数据排在后面,按照审批时间approval_time倒序排序

解决

方案一: 将待处理任务和其他状态任务分别进行查询,使用union all进行拼接 注:union的上下两个语句中不能含有order by语句,需要在查询语句外面再套一层select * from(使用Oracle数据库)

select * from ( select * from TABLE t where t.status = '0' order by t.appoint_time --待处理任务按预约时间正序排序 ) aa --不取别名也会报错 union all select * from ( select * from TABLE t where t.status '0' order by approval_time desc --其他状态任务按处理时间倒序排序 ) bb

方案二(推荐方法): 在order by中使用case when语句

select * from TABLE t order by case when t.status = '0' then 0 else 1 end, --待处理任务在前,其他在后 case when t.status = '0' then t.appoint_time end, --待处理任务按预约时间正序排序 case when t.status '0' then approval_time end desc --其他状态任务按处理时间倒序排序


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3