[英]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.