gpt4 book ai didi

mysql - 按同一列上的多个案例对行进行排序

转载 作者:可可西里 更新时间:2023-11-01 08:04:07 28 4
gpt4 key购买 nike

我有这个结构

        |   start_at
----------------------
record1 | 2016-01-20
record2 | 2016-01-15
record3 | 2016-01-22
record4 | 2016-01-10

s say that the current date it s 2016-01-19

我想首先获取 start_at 大于当前日期的记录,并按 start_at ASC 对它们进行排序。

然后我想获取 start_at 小于当前日期的记录,并按 start_at DESC 对它们进行排序。

所以结果应该是这样的:

        |   start_at
----------------------
record1 | 2016-01-20
record3 | 2016-01-22
record2 | 2016-01-15
record4 | 2016-01-10

我该怎么做?

我试过这样做,但没有成功:

ORDER BY start_at >= NOW() ASC, start_at < NOW() DESC

最佳答案

你很接近,order by 的多个键:

ORDER BY (start_at >= NOW()) desc,
(case when start_at >= NOW() then start_at end) asc,
(case when start_at < NOW() then start_at end) desc

第一个条件将 future 日期放在首位。如何?表达式 start_at >= NOW() 返回一个 bool 值。真值是“1”,假值是“0”,所以 desc 但 future 值在前。其他两个键处理每个组内的排序。

关于mysql - 按同一列上的多个案例对行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38525292/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com