Auto Update Date for Given range in SQL - 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()));

Related

Get records for past month, day and a specific 24 hour period in the past

At the moment I have:
SELECT timeslot_start_time
, name
, description
, etc
FROM Table1
WHERE Timeslot_start_time >= '2022-02-01'
ORDER BY Timeslot_start_time
Q1. Instead of doing this manually, is there a way the table only gets data that is a month old from today automatically?
Q2. Additionally, my data is in this format: 22-02-15 21:45:00, with data reading every 15 minutes. Is there a way I can create a column(/table or whatever is best) that filters only the last 24hours automatically?
Q3. Additionally, is it possible to filter the last 24hrs but from a specific time. For example filtering the last 24hrs up to 10pm, So 10pm-10pm.
I hope all of that makes sense
Your data could be queried using basic date arithmetic:
gets data that is a month old from today automatically?
"A month" is ambiguous (like past 30 days, all dates in previous month, etc). But most simple definition is to use dateadd and let SQL Server decide:
WHERE timeslot_start_time >= DATEADD(MONTH, -1, CURRENT_TIMESTAMP)
that filters only the last 24hours automatically?
WHERE timeslot_start_time >= DATEADD(DAY, -1, CURRENT_TIMESTAMP)
is it possible to filter the last 24hrs but from a specific time. For
example filtering the last 24hrs up to 10pm, So 10pm-10pm.
DECLARE #d2 DATETIME = DATETIMEFROMPARTS(
DATEPART(YEAR, CURRENT_TIMESTAMP),
DATEPART(MONTH, CURRENT_TIMESTAMP),
DATEPART(DAY, CURRENT_TIMESTAMP),
22,
0,
0,
0
);
IF #d2 > CURRENT_TIMESTAMP
-- if 10pm today is in the future then use yesterday
SET #d2 = DATEADD(DAY, -1, #d2);
SELECT ...
WHERE timeslot_start_time >= DATEADD(DAY, -1, #d2)
AND timeslot_start_time < #d2

Need help extracting SQL data for 2 previous days

I need to run a SQL script every night that extracts data from the previous 2 days. For example: On July 9 at 1am, the script runs and needs to extract data from July 8 and July 7. On July 10 at 1am, it needs to extract data from July 9 and July 8, etc.
The script is functional, in that it correctly extracts data for a fixed date range (by including the actual date range in the script), but I don't know how to make it do the "2 days prior" part.
Figuring this out is beyond me! Can anyone provide guidance?
Using SQL Server 2014
You can do:
where datecol >= convert(date, dateadd(day, -2, getdate())) and
datecol < convert(date, getdate())
That said, I would be very wary about putting this logic directly into a query. I would create a stored procedure in SQL Server and have it take #fromdate and #todate arguments.
Then, schedule a job that does the above calculation and calls the stored procedure with the right parameters.
One day, when the server is down or the logic fails, you will appreciate having the flexibility to specify the date range yourself.
I would create three variables.
#today: is the current datetime cast to a date to set it to midnight
#startDate: first/start date where I would use the DATEADD function to subtract two days
#endDate: end date that you can subtract 1 second from today
This should get you a date range of 2019-07-07 00:00:00.000 to 2019-07-08 23:59:59.000
DECLARE #today DATETIME = CAST(GETDATE() AS DATE);
DECLARE #startDate DATETIME = DATEADD(DAY, -2, #today);
DECLARE #endDate DATETIME = DATEADD(SECOND, -1, #today);
Time is usually very critical when working with dates, make sure your start date starts at the beginning of the day and your end date ends at the very end of the day!
Your query would then look like:
SELECT *
FROM my_table
WHERE my_date_column BETWEEN #startDate AND #endDate

How to change both date and time in a datetime in SQL

I try to set the time and date in my query based one the following conditions:
if time in MyDate < 9:00 then set the time to 9:00
If time in 9:00 < MyDate < 15:00 then set the time to 16:00
If time is MyDate > 15:00 then set the time to 9:00 and the day to day+1
I have the two first conditions in place and works fine, but cannot combine changes in both time and date. How can I do that?
The code below works fine for the two first conditions!
Case When cast(MyDate as TIME) < '09:00:00' Then DATEADD(Hour, 9, CAST(CAST(PayoutDtApplication As Date) As Datetime))
Case When cast(MyDate as TIME) < '09:00:00' Then DATEADD(Hour, 9, CAST(CAST(PayoutDtApplication As Date) As Datetime))
THanks
This is a guess, based on the following comment:
this numbers can varries based on the data I get, just wanted to say I need to set the time to 9:00 and day+1 for all dates I get. I have different dates.
I'm guessing that regardless of the time, the OP wants to change the value to the following date at 09:00:00.
If so, one way to achieve it would be:
SELECT DATEADD(HOUR, 33, CONVERT(date,YourDateColumn)) AS NewDate
FROM YourTable;
Again, this is guesswork. If the OP elaborates, I'll be happy to expand my answer, or remove it if it's irrelevant.
Edit: Based on the OP's new logic from their edit:
CREATE TABLE #Sample (YourDate datetime2(0));
INSERT INTO #Sample
VALUES ('2018-05-09T08:57:00'),
('2018-05-09T14:26:37'),
('2018-05-09T19:24:01');
GO
SELECT YourDate,
CASE WHEN CONVERT(time, YourDate) < '09:00:00' THEN DATEADD(HOUR,9,CONVERT(datetime2(0),CONVERT(date,YourDate)))
WHEN CONVERT(time, YourDate) > '15:00:00' THEN DATEADD(HOUR,33,CONVERT(datetime2(0),CONVERT(date,YourDate)))
ELSE DATEADD(HOUR,15,CONVERT(datetime2(0),CONVERT(date,YourDate))) END AS NewDate
FROM #Sample;
GO
DROP TABLE #Sample;
The double CONVERT (CONVERT(datetime2(0),CONVERT(date...) is because the data type date isn't compatible with DATEADD(HOUR.... I have used datetime2 as this should be used over datetime now.

SQL query to start from hour 12:00 am

I have a date column like this 7/24/2017 and when I write the below where clause I get results from hour 7/24/2017 1:00:00.000 AM. I need to get this from 7/24/2017 12:00:00.000 AM. How should this where clause me modified. Please check the following code
Date>= DATEADD(day, -1, convert(date, GETDATE())) and
Date< DATEADD(day, +0, convert(date, GETDATE()))
There doesn't appear to be anything wrong with your code. Are you certain your data contains any times before 1am? Are you certain you appreciate how your SQLServer will format those times/represent them to you?
See this SQLFIDDLE: http://sqlfiddle.com/#!6/047cc/11
Optimisations: you don't need to dateadd a value of 0. You can also subtract 1.0 from a date to get the day earlier and it's a bit less wordy than DATEADD. It works because internally dates are represented as floating point numbers of the number of days since a point in time:
[Date] >= convert(date, GETDATE() -1.0) and
[Date] < convert(date, GETDATE())

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

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.