SQL query to check if a date is close to today
Here's a table:
orders(id, item, deliveryDate, courier_id)
I'd like to write a query that will return all orders for a given courier with a delivery date that's within a month of toda开发者_JS百科y. How do I do that?
Most servers use the integer part of the date for days.
In this example I use "Now()" as a server function that returns the current date. You should look the right one on the documentation of the server you use.
(also the ? mark as the value of courier id)
Select *
From orders
Where Now() - deliveryDate < 30
And courier_id = ?
If your server does not hold days - you can look on it's date-conversion functions
In T-SQL:
SELECT *
FROM orders
WHERE deliveryDate BETWEEN GETDATE() AND GETDATE() + 30
AND courier_id = @CourierID
EDIT
While the period in this solution is calculated to be roughly a month, it is not precisely one month, as uncle brad has neatly observed. If you need to be precise, you should calculate one month from the current date like this: DATEADD(month, 1, GETDATE())
. This replaces GETDATE() + 30
in the above query.
If MySQL
DATE_ADD
SELECT * FROM orders WHERE deliveryDate BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 1 MONTH);
精彩评论