Query previous day with GETDATE()-1 and a time period from/to - sql

I want to get total counts from SuperScottTable1 from the previous day and narrow to a time frame (From-To). The below works fine until I add
AND (time > '08:00:00.000' AND time < '22:00:00.000')
It does not error, just returns null.
Is this possible to do?
SELECT
SUM(COALESCE(confirmedCount, 0))
FROM
SuperScottTable1
WHERE
superLaneID = '90099'
AND time >= GETDATE()-1
AND (time > '08:00:00.000' AND time < '22:00:00.000')

You can do some CAST/CONVERT shenanigans to generate a starting and stoping DATETIME value which you can then compare to your time column. If the time column is indexed then this will allow the server to do a simple range search on the index to find matches.
WHERE
superLaneID = '90099'
AND time > CAST(CONVERT(VARCHAR(20), GETDATE()-1, 112) + ' 08:00:00' AS DATETIME)
AND time < CAST(CONVERT(VARCHAR(20), GETDATE()-1, 112) + ' 22:00:00' AS DATETIME)

Presumably, time is stored as a datetime. You seem to be using SQL Server, so you can extract the hour and use that:
WHERE superLaneID = '90099' AND
time >= GETDATE()-1 AND
datepart(hour, time) >= 8 AND
datepart(hour, time) < 22
EDIT: To get the "other" hours:
WHERE superLaneID = '90099' AND
time >= GETDATE()-1 AND
(datepart(hour, time) < 8 or
datepart(hour, time) >= 22
)

GETDATE() in SQL Server returns the system date and time to arrive at the current day (i.e. date at time 00:00:00.0000000) you can use either of these:
cast(getdate() as date) -- available from SQL 2008 onward
dateadd(day, datediff(day,0, getdate() ), 0) -- any SQL Server version
Using these to establish the current date, then add (8-24) hours and or (22-24) hours to establish the boundaries of yesterday e.g.
WHERE superLaneID = '90099'
AND time >= dateadd(hour,(8-24),cast(getdate() as date))
AND time < dateadd(hour,(22-24),cast(getdate() as date))
Avoid using non-sargable predicates (such as using a function) that require you to alter each row of data to compare to a fixed value. ref this prior answer
Btw: This method discussed here would work for a time range that spans midnight.

Related

Auto Update Date for Given range in SQL

I have a SQL query by which I have to extract data from the server but every time I have to change the date range
where date(usf.created_date) BETWEEN '2022-04-01 00:00:00' and '2022-04-30 23:59:59'
but I want to get this range auto-update from today 30 days back.
I have tried the casting method Cast(GETDATE() as smalldatetime) but it shows an error in the same.
Assuming based on GETDATE() that this is SQL Server, you either want:
-- get everything going back exactly 30 days from this moment
WHERE usf.created_date >= DATEADD(DAY, -30, GETDATE());
Or:
-- get everything going back 30 days from this morning at midnight
WHERE usf.created_date >= DATEADD(DAY, -30, CONVERT(date, GETDATE()));

Rounding DateTime in SQL

I have DateTime data in a MS SQL database with the following format:
2020-05-07 22:35:00
I am trying to create a query that only captures data from the last 24 hours of operations. However, our operations KPIs are measured from 6AM-6AM. I would like to round the date based on time. Anything before 6AM will be counted as the day before.
2020-05-07 05:45:00 -> 2020-05-06 (Before 6AM)
2020-05-07 06:30:00 -> 2020-05-07 (After 6AM)
So far I have been successful in pulling the previous days activity, but am struggling to shift the timeframe to round down anything before 6AM
SELECT
end_date
FROM data sint
WHERE sint.end_date >= dateadd(day,datediff(day,1,GETDATE()),0)
AND sint.end_date < dateadd(day,datediff(day,0,GETDATE()),0)
You can add six hours to the current date (without the time) for the comparison:
where int.end_date < dateadd(hour, 6, convert(datetime, convert(date, getdate()))) and
int.end_date >= dateadd(hour, 6 - 24, convert(datetime, convert(date, getdate())))
Note that the conversion to date removes the time component.
first get the time part. Compare the time part with 6AM and run your expression.
In below code the time part is compared with the date '1900-01-01 06:00:00' which is 6AM in default date format.
select
case when cast(date as time(0)) < '1900-01-01 06:00:00'
then cast(date - 1 as date)
else cast(date as date)
end as newdate
from temp_date;
I would do the same as Gordon only the opposite side.
I would subtract 6 hours from end_date and then compare.
where convert(date, dateadd(hour, -6, int.end_date)) = convert(date, getdate())
Though this method might not work well if you're actually using getdate(). It will return nothing if it is ran between midnight and 6 am (unless you have future dates).

GETUTCDATE but specify custom time

I'm trying to write an automation code for which I want to use the current date but the time must be specific.
SELECT
col_name
FROM
table
WHERE
CONVERT(DATE, start_datetime) = CONVERT(date, GETUTCDATE())
How do I mention specific time?
wow took me a minute I wasn't understanding your question. but I think you are asking how do you specify a time today and compare that to your start_datetime value to see if they are at the same time.
The question will come down to how accurate do you want to be. e.g. at a specific hour? within x # of minutes? Seconds....????
And there are tons of ways of answering this.
The first question is what timezone is your start_datetime stored in? Because you likely do not want to use UTC Date if your start_date is not also in UTC! If not utc what timezone is your server set to, would GETDATE() and start_datetime be in the same zone?
Anytime Today in a specific hour.
SELECT
col_name
FROM
table
WHERE
CONVERT(DATE, start_datetime) = CONVERT(date, GETUTCDATE())
AND HOUR(start_datetime) = 5
Anytime Today at specific hour and minute
SELECT
col_name
FROM
table
WHERE
CONVERT(DATE, start_datetime) = CONVERT(date, GETUTCDATE())
AND DATEPRT(HOUR,start_datetime) = 5
AND DATEPART(MINUTE,start_datetime) = 15
OR
SELECT
col_name
FROM
table
WHERE
start_datetime = CAST(CAST(GETUTCDATE() AS DATE) AS DATETIME) + CAST('05:15' AS DATETIME)
OR
SELECT
col_name
FROM
table
WHERE
start_datetime = CONVERT(DATETIME,(CONVERT(VARCHAR(10),GETUTCDATE(),120) + ' 19:15'))
For seconds you can use basically the same technique as the hour/minute only add an either seconds to the string you are converting or
For after a specific time just switch the = to >

Get tomorrows date

I am trying to get tomorrows date in a sql statement for a date comparison but it is not working.
Below is my code:
select *
from tblcalendarentries
where convert(varchar,tblcalendarentries.[Start Time],101)
= convert(varchar, GETDATE() +1, 101)
To get tomorrows date you can use the below code that will add 1 day to the current system date:
SELECT DATEADD(day, 1, GETDATE())
GETDATE()
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
DATEADD(datepart , number , date)
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
So adding this to your code in the WHERE clause:
WHERE CONVERT(VARCHAR, tblcalendarentries.[Start Time], 101) =
CONVERT(VARCHAR, DATEADD(DAY, 1, GETDATE()), 101);
First off, GETDATE() will get you today's date in the following format:
2013-04-16 10:10:02.047
Then using DATEADD(), allows you to add (or subtract if required) a date or time interval from a specified date. So the interval could be: year, month, day, hour, minute etc.
Working with Timezones?
If you are working with systems that cross timezones, you may also want to consider using GETUTCDATE():
GETUTCDATE()
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
Try the below:
SELECT GETDATE() + 1
This adds one day to current date
Specify size of varchar in convert()
where convert(varchar(11),tblcalendarentries.[Start Time],101) = convert(varchar(11), GETDATE() +1, 101)
I would write:
where
DATEADD(day,DATEDIFF(day,0,tblcalendarentries.[Start Time]),0) =
DATEADD(day,DATEDIFF(day,0,GETDATE()),1)
This avoids converting dates to strings entirely, whilst also removing the time portion from both values.

Easier way to compare a DATE field to the date value of GETDATE?

I have a field in a table Event.EventDate and it's of the data type DATE rather than DATETIME and then I have a view that has the following WHERE clause:
WHERE e.EventDate >= CAST(CONVERT(VARCHAR(MAX), GETDATE(), 101) AS DATETIME)
As you can see, I'm just trying to get all events >= today's date. The above code works, but it's ugly. I tried this ...
WHERE e.EventDate >= CONVERT(VARCHAR(MAX), GETDATE(), 101)
... and this ...
WHERE e.EventDate >= CONVERT(DATETIME, GETDATE(), 101)
... but those didn't work, they gave me every event > today's date. However, even if the above worked, it's still ugly.
Isn't there a better way?
Try:
WHERE e.EventDate >= cast(getdate() as date)
To cast getdate() into a date time. It's a clean way in SQL Server 2008 and up to strip out the time portion of a datetime type.
Using Shan Plourde's method is certainly cleaner and quicker, but for the more general case when you want to round a datetime to a particular time interval, I use
dateadd(dd,datediff(dd,0,[datetime column]),0)
where dd stands for day, and can be replaced with mm (month), hh (hour), mi (minute), and probably others.
If you want to get fancy and round to, say, 15 minute intervals, you can use
dateadd(mi,
-datepart(mi,[datetime column])%15,
dateadd(mi,datediff(mi,0,[datetime column]),0)
)
where % is the modulo operator. You'll get wacky results for this if you don't use an interval that divides 60 evenly.