Today是:2017-10-14
,下面是事件日期表:
...
2017-10-18
2017-10-17
2017-10-16
2017-10-14
2017-10-12
2017-10-10
2017-10-09
....
我想像这样对表格进行排序
...
2017-10-14
2017-10-16
2017-10-17
2017-10-18
2017-10-12
2017-10-10
2017-10-09
....
如何使用 MySQL 做到这一点?
尝试这样的事情
ORDER BY CASE
WHEN eventdate = Cast(now() AS DATE) THEN 1
WHEN eventdate < Cast(now() AS DATE) THEN -1
ELSE 0
END DESC,
case when eventdate < Cast(now() AS DATE) then eventdate end desc,
case when eventdate > Cast(now() AS DATE) then eventdate end asc
只需使用两个CASE
表达式即可完成所需的排序。 第一种情况将当前和未来的事件与以前的事件分开。 第二种情况按当前和未来事件的升序和先前事件的降序排列。
SELECT
date
FROM yourTable
ORDER BY
CASE WHEN date >= CURDATE() THEN 0 ELSE 1 END,
CASE WHEN date >= CURDATE()
THEN UNIX_TIMESTAMP(date) ELSE -UNIX_TIMESTAMP(date) END;
输出:
date
1 14.10.2017 00:00:00
2 16.10.2017 00:00:00
3 17.10.2017 00:00:00
4 18.10.2017 00:00:00
5 12.10.2017 00:00:00
6 10.10.2017 00:00:00
7 09.10.2017 00:00:00
在这里演示:
Rextester
MySQL方便地将布尔值视为数字上下文中的数字。 所以一个简单的方法是:
where (datecol >= curdate()) desc, -- put future dates first,
(case when datecol >= curdate() then datecol end) asc,
datecol desc
我喜欢有第一个条件,所以排序的意图非常清楚。
order by
case when DateCol >= cast(now() as date) then DateCol
-- ^^ I use this cast is needed to ignore time part of comparing
else now() - DateCol
end
SQL 小提琴演示