根据 "status" 字段值(运行、即将到来、已关闭)对记录进行排序,记录应基于 mysql 中的日期

Sort records based on "status" field value (running, upcoming, closed) and the records should come based on date in mysql

我需要根据“状态”字段值(运行、即将到来、已关闭)顺序对记录进行排序,还有一个条件是它应该基于日期。

假设 20-08-202121-08-2021 有如下 7 条记录

title date time status
R1 20-08-2021 08:00:00 closed
R2 20-08-2021 12:00:00 upcoming
R3 20-08-2021 16:00:00 running
R4 21-08-2021 9:00:00 running
R5 21-08-2021 15:00:00 closed
R6 21-08-2021 19:00:00 upcoming
R7 21-08-2021 14:00:00 closed

结果应该是这样的

title date time status
R3 20-08-2021 16:00:00 running
R2 20-08-2021 12:00:00 upcoming
R1 20-08-2021 08:00:00 closed
R4 21-08-2021 9:00:00 running
R6 21-08-2021 19:00:00 upcoming
R7 21-08-2021 14:00:00 closed
R5 21-08-2021 15:00:00 closed

注意:这里有一项规定可以开始任何未来日期的事件,因此我们可以让未来日期事件具有 运行 并且 R7 应该排在第一位,因为它的开始时间小于 R5。

我用过order by case但是有没有什么有效的方法可以轻易破解而且order by case也解决不了

先用ROW_NUMBER()window函数对每个状态的行进行排序,然后查看每个状态的值:

SELECT *
FROM tablename
ORDER BY ROW_NUMBER() OVER (PARTITION BY status ORDER BY date, time), 
         status = 'running' DESC,
         status = 'upcoming' DESC,
         status = 'closed' DESC;

如果您的 MySql 版本不支持 window 函数,请使用相关子查询:

SELECT t1.*
FROM tablename t1
ORDER BY (
           SELECT COUNT(*) 
           FROM tablename t2 
           WHERE t2.status = t1.status 
             AND CONCAT(t2.date, t2.time) <= CONCAT(t1.date, t1.time)
         ), 
         status = 'running' DESC,
         status = 'upcoming' DESC,
         status = 'closed' DESC;

参见demo