SQL 获取最近的日期记录

SQL get nearest date record

这是一个示例数据:

 Booking_id   Name   start_date
   1            abc   1/1/2018
   2            efg   5/2/2018
   3            pqr   16/1/2018
   4            xyz   19/2/2018

我希望这是最接近今天的日期在最上面和过去的日期在最后的顺序

使用sql的ORDER BY功能。像这样:

SELECT * 
FROM 
     table_name 
ORDER BY 
   start_date DESC;

根据我的理解,下面是您的问题,请进一步告诉我。

用户可以根据需要使用 Order by with ASC|Desc,

select * from booking_table order by start_date DESC;

您需要 SORT descstart_Date 上的函数。以下是将产生您想要的结果的查询。

select * from table1
order by Start_Date desc;

你可以查看sqlfiddle演示here

如果日期在未来,您必须使用 asc 来获得您想要的结果。

select * from table1
order by Start_Date asc;

如果您的日期是过去和未来日期的混合,如下面的示例数据。

ID Name   Start_Date
---------------------
1  abc   2018-01-01
2  efg   2018-02-05
3  pqr   2018-01-16
4  xyz   2018-02-19
1  abc   2017-01-01
2  efg   2017-02-05
3  pqr   2017-01-16
4  xyz   2017-02-19

下面的查询可以是一个以更友好的格式显示数据的选项。

select * from (
select * from table1
where start_date < current_date
order by start_date desc
) as B
union
select 0,'TODAY_DATE', current_date
union
select * from (
select * from table1
where start_date > current_date
order by start_date asc
) as A 

它将按 desc 顺序对过去日期数据进行排序,然后将 TODAY 日期添加到结果中,然后以 asc 格式添加未来数据,如下所示。

 ID  Name        Start_Date
--------------------------
4   xyz         2017-02-19
2   efg         2017-02-05
3   pqr         2017-01-16
1   abc         2017-01-01
0   TODAY_DATE  2017-08-18
1   abc         2018-01-01
3   pqr         2018-01-16
2   efg         2018-02-05
4   xyz         2018-02-19

查看 SQLfiddle 演示 here

您想要最近的日期,以便您可以尝试以下查询

SELECT * FROM table 
WHERE start_date >= now()
ORDER BY start_date ASC;

如果你想要它以崇高的顺序,那么:

SELECT * FROM table 
WHERE start_date <= now()
ORDER BY start_date DESC;

您可以使用以下查询:

SELECT Booking_id, Name, start_date
FROM mytable
ORDER BY ABS(DATEDIFF(start_date, NOW()));

ORDER BY 子句按距今天日期的天数排序。距离最小的日期在前。

Demo here

这对你有用,

select * from table_name Order By start_date Desc;

根据您的其中一条评论:

today's records follow by future records and then old records at the end

这将首先对今天和未来的日期进行排序,然后是过去的日期:

ORDER BY 
   CASE WHEN start_date >= CURRENT_DATE THEN 1 ELSE 2 END,
   start_date

结果新旧日期均按升序排序,如果您希望旧日期按降序排序:

ORDER BY 
   CASE WHEN start_date >= CURRENT_DATE THEN 1 ELSE 2 END,
   ABS(CURRENT_DATE - start_date)