簡體   English   中英

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

我希望這是最接近今天的日期和最后一個的過去日期的順序

您需要在start_Date列上使用SORT desc函數。 下面是查詢,它將產生您想要的結果。

select * from table1
order by Start_Date desc;

您可以在此處查看sqlfiddle演示

如果日期是將來的日期,則必須使用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演示

使用sql的ORDER BY函數。 像這樣:

SELECT * 
FROM 
     table_name 
ORDER BY 
   start_date DESC;

根據我的理解,以下是您的查詢,請讓我進一步了解。

可以根據需要使用ASC | Desc使用Order by,

select * from booking_table order by start_date DESC;

您想要最近的日期,以便嘗試進行后續查詢

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子句按距離今天日期的天數排序。 距離最小的日期排在第一位。

在這里演示

這對你有用

select * from table_name Order By start_date Desc;

根據您的評論之一:

今天的記錄,之后是將來的記錄,最后是舊記錄

它將首先排列今天和將來的日期,然后是過去的日期:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM