简体   繁体   中英

SQL query to select range from specific date/time yesterday to specific date/time current day

SELECT * 
FROM services 
WHERE service_date BETWEEN (dateadd(DD, -1, getdate())) AND (dateadd(DD, 1, getdate())) **---Gives us a last one day data.**

but what we really need is data from 07:00 AM yesterday to 06:59 AM current day, so I tried the following:

SELECT * 
FROM services 
WHERE service_date BETWEEN (dateadd(DD, -1,((DatePart(hh, getdate())) >= 7 ))) **-- Expecting to pull from yesterday 07:00** 
                   AND (dateadd(DD, -1,((DatePart(hh, getdate())) <= 6 ))) **-- to current day till 06:59**

but the system didn't like my SQL skills ...PLEASE HELP...!

These will get you the dates you are looking for...

Select DATEADD(HOUR,-17, (DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)))


Select DATEADD(HOUR,7, (DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)))

I'm not sure if this is the most effective way but it works.

Assuming you are on SQL Server:

Select *
From MyTable
Where MyDateColumn Between DATEADD(hh, 7, Cast(Cast(DATEADD(d, -1, CURRENT_TIMESTAMP) As Date) As DateTime)) 
                       And DATEADD(hh, 6, Cast(Cast(CURRENT_TIMESTAMP As Date) As DateTime))

UPDATE: I agree with Andy's solution. Similar approach but his solution is much more elegant and efficient.

Try something like that:

SELECT * 
FROM services 
WHERE service_date
      BETWEEN Convert(DateTime, Convert(nchar(4), DatePart(YYYY, GETDATE())) + '-' 
+ Convert(nchar(2), DATEPART(MM, GETDATE())) + '-' 
+ Convert(nchar(2), DATEPART(DD, Getdate())-1) + ' 7:00:00')
      AND Convert(DateTime, Convert(nchar(4), DatePart(YYYY, GETDATE())) + '-' 
+ Convert(nchar(2), DATEPART(MM, GETDATE())) + '-' 
+ Convert(nchar(2), DATEPART(DD, Getdate())) + ' 6:59:00')

The idea is to take the year, month and day from today (or yesterday), and form a new date by concatenate them.

Beware of the culture settings for date format and do some testing before put this code into production.

You could also use mi (minutes) with DateAdd . Adding 419 minutes to midnight to get 06:59 and a nice round 420 minutes to yesterday midnight for 07:00

Edit : Changed the DateDiff function to work with Sybase.

SELECT *
FROM services
WHERE service_date BETWEEN DATEADD(mi, 420, DATEADD(d, -1, DATEDIFF(d, DATE('1900-01-01'), GETDATE()))) 
                       AND DATEADD(mi, 419, DATEADD(d, -0, DATEDIFF(d, DATE('1900-01-01'), GETDATE())));

Edit : Removing DateDiff function

SELECT *
FROM services
WHERE service_date BETWEEN DATEADD(mi, 420, DATEADD(d, - 1, Convert(VARCHAR(10), GETDATE(), 111)))
                       AND DATEADD(mi, 419, DATEADD(d, - 0, Convert(VARCHAR(10), GETDATE(), 111)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM