Adding Current Values to future Dates SQL - sql

I'm trying to load data for future dates. My scenario is something like this, I have data for 2016, 2017 and 2018(until August). Each year has Current and 'Prior Year Same Day' values associated. Data is aggregated to Month. Requirement is that I load data for future dates as well, that is for September 2018 through August 2019 using 'PYSD' values. For example, the 'Current' value for September 2017 will be 'PYSD' value for September 2018 and so on. When I try this particular logic I get an error stating 'overflow' and I'm unable to figure out what's causing. This happens only with the second condition in my WHERE clause. My SELECT clause aggregates a months' data and outputs as '08-01-2018' - there will be one row per month/year.
SELECT
CAST(YEAR(DATEADD(dd, 364, CalendarDate)) AS VARCHAR(250))
+ '-' + RIGHT('00' + CAST(MONTH(DATEADD(dd, 364, CalendarDate)) AS VARCHAR(250)), 2)
+ '-' + '01' AS MonthPeriod
FROM
DateTable
WHERE
DATEADD(DD, 364, CalendarDate) > '08-31-2018'
AND DATEADD(DD, 364, CalendarDate) < '08-01-2019'
My error:
Msg 517, Level 16, State 3, Line 1
Adding a value to a 'date' column caused an overflow.
Also, open to suggestions if there is a simpler way. I'm on SQL Server.
TIA.
Added sample data:

As you stated in one of the answers to the original question, your max date is 9999-12-31
This means that any sort of DATEADD(DD, 364, CalendarDate) should always fail. Doesn't matter if you are trying to check against a date in 2018, because it has to do the dateadd first, and that gets an overflow.
To avoid that overflow do your date add the other way - compare the actual CalendarDate to one year before your target date.
CalendarDate > DATEADD(DD, -364, '08-31-2018')
or just
CalendarDate > '2017-08-31'
I'll leave the rest of how you should specify the date, or whether it should be 364,365,first of month etc to the rest of the discussion.

What is the maximum date in your DateTable ? You probably have dates that is with year 9999. So adding 364 will cause it to overflow. It has nothing to do with the SELECT clause
On your query, you can simply do this
SELECT DATEADD(MONTH,
DATEDIFF(MONTH, 0,
DATEADD(DAY, 364, CalendarDate)), 0) AS MonthPeriod
Note :
DATEADD(MONTH, DATEDIFF(MONTH, 0, <date>), 0) will gives you the 1st day of the month
EDIT :
The overflow error is because the DateTable contains rows with date 9999. Adding 364 days to it will cause over flow.
One quick way to resolve is to delete those rows where year is 9998 or 9999
Another way is to change your query such that it does not add days to the CalendarDate
WHERE CalendarDate > DATEADD(DAY, 364, '2018-08-31')
AND CalendarDate < DATEADD(DAY, 364, '2019-08-01')
Note : i uses date string in ISO format YYYY-MM-DD. It is recommended to specify date in such format as it is unambiguous.
And the complete query will be
SELECT DATEADD(MONTH,
DATEDIFF(MONTH, 0,
DATEADD(DAY, 364, CalendarDate)), 0) AS MonthPeriod
FROM DateTable
WHERE CalendarDate > DATEADD(DAY, 364, '2018-08-31')
AND CalendarDate < DATEADD(DAY, 364, '2019-08-01')

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

Pulling data from Sybase SQL database using rolling window

I wish to pull three years of data from a database but right now I have to specify the dates in a number of sections in my code using a between statement:
BETWEEN '2015-10-01' AND '2018-09-30'
Since the database only contains valid data from the previous month backwards, I wish to take the end of the last month and go back three years.
I found this tutorial where the author shows how to do this in SQL server and I've tried to adapt it but my RDBMS is throwing errors in the datediff function
----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
My code looks as follows but I the error I am seeing is about converting 0 to a date.
DECLARE #date DATE
SET #date = getdate()
SELECT dateadd(second,-1,dateadd(mm, DATEDIFF(m,0,GETDATE()),0))
If anyone has any suggestions I would be very grateful for your guidance.
In your WHERE clause, you could use this condition:
DATEDIFF(month, [YourDateColumn], GETDATE()) BETWEEN 1 AND 36
Your current code looks good without any error, but you can use EOMONTH() instead.
However, the difference would be in return types your code would return date-time while eomonth() would return date only.
DECLARE #date DATE
SET #date = getdate()
SELECT EOMONTH(#date, -1)
Don't use between and the job becomes far easier. Use less than the first day of the current month which accurately locates everything before that date (instead of last day of previous month). Subtract 3 years from that same date and use >= for the starting point.
Select *
From yourtables
where datecol >= dateadd (year,-3,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0) )
And datecol < DATEADD(mm,DATEDIFF(m,0,GETDATE()),0)
Please don't use any solution that use 23:59:59 as the end of a day. It is not the end of a day and several data types now support sub-second time precision.
If you really cannot use zero in the date functions simply use the base date of '1900-01-01' instead
SELECT
DATEADD(YEAR, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), '1900-01-01'))
, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), '1900-01-01')
;
This should also work (it does in this demo here):
SELECT
DATEADD(YEAR, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0))
, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), 0)
;

SQL Date only in Where clause [duplicate]

If I have a date value like 2010-03-01 17:34:12.018
What is the most efficient way to turn this into 2010-03-01 00:00:00.000?
As a secondary question, what is the best way to emulate Oracle's TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?
To round to the nearest whole day, there are three approaches in wide use. The first one uses datediff to find the number of days since the 0 datetime. The 0 datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;
select dateadd(d, 0, datediff(d, 0, getdate()))
The second method is text based: it truncates the text description with varchar(10), leaving only the date part:
select convert(varchar(10),getdate(),111)
The third method uses the fact that a datetime is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using floor, you get the start of the day:
select cast(floor(cast(getdate() as float)) as datetime)
To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:
select dateadd(dd, 1 - datepart(dw, getdate()), getdate())
This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with #start_of_day as a variable for readability:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, #start_of_day), #start_of_day)
The start of the year, month, hour and minute still work with the "difference since 1900" approach:
select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)
Rounding by second requires a different approach, since the number of seconds since 0 gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, #start_of_day, getdate()), #start_of_day)
To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using /5*5:
select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)
This works for quarters and half hours as well.
If you are using SQL Server 2008+, you can use the Date datatype like this:
select cast(getdate() as date)
If you still need your value to be a DateTime datatype, you can do this:
select cast(cast(getdate() as date) as datetime)
A method that should work on all versions of SQL Server is:
select cast(floor(cast(getdate() as float)) as datetime)
Try:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
UPDATE: answer on the second question:
for years you could use a little bit modified version of my answer:
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
for quarter:
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
and so on.
I checked, up to minutes - it's OK. But on seconds I've got an overflow message:
Difference of two datetime columns
caused overflow at runtime.
One more update: take a look to the following answer to the same question
This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.
declare #SomeDate datetime = '2010-03-01 17:34:12.018'
SELECT
DATEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01'
) AS CUR_DATE_FROM_PARTS
,DATETIMEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01' --DAY(#SomeDate)
,'00' --DATEPART(HOUR,#SomeDate)
,'00' --DATEPART(MINUTE,#SomeDate)
,'00' --DATEPART(SECOND,#SomeDate)
,'00' --DATEPART(MILLISECOND,#SomeDate)
) AS CUR_DATETIME_FROM_PARTS
,#SomeDate AS CUR_DATETIME
,YEAR(#SomeDate) AS CUR_YEAR
,MONTH(#SomeDate) AS CUR_MONTH
,DAY(#SomeDate) AS CUR_DAY
,DATEPART(HOUR,#SomeDate) AS CUR_HOUR
,DATEPART(MINUTE,#SomeDate) AS CUR_MINUTE
,DATEPART(SECOND,#SomeDate) AS CUR_SECOND
,DATEPART(MILLISECOND,#SomeDate) AS CUR_MILLISECOND
FROM Your_Table
Truncated Date: 2010-03-01
Truncated DateTime: 2010-03-01 00:00:00.000
DateTime: 2010-03-01 17:34:12.017
Not sure if this is the most efficient, but I like the simplicity in using the following where #SomeDate is your field.
Concat(Year(#SomeDate), '-', Month(#SomeDate), '-', '01')
If you want to truncate a date to the start of the week in a way that is independent of SET DATEFIRST you can:
--change a date backwards to nearest Monday
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN)
Breaking this down:
DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN): the dw of a known Monday (2001-01-01 was a Monday) minus the dw of your date, effectively giving the "number of days difference between your date and Monday" or "how many days back do we have to scroll your date to make it into Monday"
( ... -7)%7 - we subtract 7 from it and modulo the result by 7.
We do this because if e.g. DATEFIRST is 7 (Sunday), and your date column is Sunday then your dw is 1, and your known Monday is 2.
This means the result of the dw_for_known_monday - dw_for_your_date is +1 rather than -6
This would then mean that DATEADD will roll your date forwards to the following Monday rather than backwards to the previous Monday
If we subtract 7 off it then the result would definitely be negative, but then we wouldn't want your Mondays (which are 0 days different from the known Monday) to end up doing a DATEADD of -7, so we modulo the result by 7.
This turns any problematic -7 into 0, which means your DATEADD will only ever have a "number of days" argument between -6 and 0
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN) - we then DATEADD the (negative) number of days from the above step
If you want to roll your date backwards to e.g. a Sunday, change the date 2001-01-01 to a date that is a known Sunday (like 2000-12-31), etc

Break this simple SQL/HQL Query down - DATEADD, DATEDIFF?

select * from table
where Date BETWEEN DATEADD(dd, DATEDIFF(dd, 84, GETDATE()),0)
and DATEADD(dd, DATEDIFF(dd, 77, GETDATE()),0)
Can someone please explain what this query is doing? Specifically, what is the function of DATEADD and DATEDIFF in this query?
They're trying to get the membership renewals between 84 and 77 days ago, stripping out the time.
GETDATE() returns the datetime but the user isn't interested in the time.
DATEDIFF(dd, 84, GETDATE()) gets the number of days between the current date and the 84th day after Jan 1, 1900.
DATEADD(dd, # days from above, 0) adds those number of days to Jan 1, 1900.
The net is you get 84 days ago at 00:00:00 AM.
If you just did DATEADD(dd, -84, GETDATE()) then you'd have 84 days ago + the current time.
Other ways to do the same thing are to cast the datetime to a date (assuming MS SQL Server).
.. CAST((GETDATE() - 84) AS DATE)
.. CAST(DATEADD(day, -84, GETDATE()) as DATE)
Your expression is using SQL Server syntax to convert a datetime to a date (that is, to remove the date component. The format is quite arcane, because the expression is doing getdate() - 84 as an integer and then adding this to the 0 date. The elimination of the "time" component occurs because the datediff() returns an integer.
I don't think this will work in HQL. For instance, the dd should be 'dd' and HQL has a different method of getting the current date.
And, in more recent versions of SQL Server, you can just do cast(getdate() - 84 as date).

Simplest way to create a date that is the first day of the month, given another date

In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)
To run this on a column, replace GetDate() with your column name.
The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value.
SELECT DATEADD(mm, DATEDIFF(mm, 0, #date), 0)
Something like this would work....
UPDATE YOUR_TABLE
SET NewColumn = DATEADD(day, (DATEPART(day, OldColumn) -1)*-1, OldColumn)
Just use
DATEADD(DAY, 1-DAY(#date), #date)