I want to get the ID numbers for the last 24 hour range. Say I run a task at 4:00AM each morning and want to get the previous 24 hours of data going back to 4:00AM the previous day. I need to get the id codes to search the correct tables. If the data is like this what would be the best way to query the ID numbers?
ID | Start Time | EndTime |
---|---|---|
2112 | 2021-08-10 23:25:28.750 | NULL |
2111 | 2021-08-06 17:42:27.400 | 2021-08-10 23:25:28.750 |
2110 | 2021-08-03 20:21:14.093 | 2021-08-06 17:42:27.400 |
So if I had the date range of 8/10 – 8/11 I would need to get two codes. 2111 and 2112. If I need to get 8/11 – 8/12 I would only get 2112 as the endtime is null.
Any thoughts on the best way to query this out?
Advertisement
Answer
You need to do something like that :
DECLARE @employee TABLE( ID int, StartTime datetime, EndTime datetime ) INSERT INTO @employee SELECT '2112','2021-08-10 23:25:28.750',NULL INSERT INTO @employee SELECT '2111','2021-08-06 17:42:27.400','2021-08-10 23:25:28.750' INSERT INTO @employee SELECT '2110','2021-08-03 20:21:14.093','2021-08-06 17:42:27.400' SELECT ID,* from @employee where EndTime >= GETDATE()-1 OR EndTime is null
It will takes -1 day from execution time . So if you execute it right now you will heave only null value in output – because now it’s 14.08 and this Edtime is null ( still running i think ).