How do I pull data from 30 months ago and prior? - sql-server

I am trying to automate my code so that it can only pull data from 30 months ago, since that is around when a data set is fully complete for the year. So for example, when it is July 1st, 2019, the code should pull from January 1st 2017 which is 30 months prior. I thought that the code I wrote would do this, but there are still instances of 2018 records showing up. Am I properly using this dateadd function?
select *
from table
where month(period_end) <= month(dateadd(month, -30, getdate()))
This runs fine, but 2018 records are still showing up when I should only see 2017 and before.

The issue is with the use of the MONTH() function -- that returns a number, 1-12, so you're actually comparing the month number of period_end against the month number 30 months ago. Replace your WHERE with
WHERE period_end <= DATEADD(MONTH, -30, GETDATE())

Simplify it, you don't need month():
where period_end <= dateadd(month, -30, getdate())
dateadd(month, -30, getdate()) returns the maximum date you want period_end to compare to.

Related

Is there a convenient way to compare week-over-week data in SQL?

I have a table full of daily aggregate data, but I occasionally need to pull weekly aggregate data, and provide info on increases or decreases. For that reason, I was considering using T-SQL DATEPART functionality to get week-number and year info for dates.
For example, I can get the following info using today's date (9/11/2020):
#nowWeekNumber int = datepart(wk,#today), --yields 37
#nowYear int = datepart(year,#today), --yields 2020
Using that logic, I could then gather info on records where year is 2020 and weekNumber is 36, and then I could compare those numbers to get a weekly increase/decrease. (Or maybe I'd compare weeks 35 and 36 to ensure that I'm dealing w/ entire weeks, but you get the picture)
However, if the date is 2021-01-03, that's going to return a year of 2021, and a weekNumber of 2. If I subtract a week, I'm going to get year 2021 and weekNumber 1. That weekNumber is only going to contain January 1st and 2nd, because 12/27 thru 12/31 are considered year 2020 and weekNumber 53 (even though the calendar week is 12/27 thru 1/2).
In other words, I don't think I can use weekNumber to gather weekly data, even though that would be fairly convenient. I'm aware that I can use DATEADD functions to grab the start and end-date for consecutive weeks, and I can then gather aggregate data for records BETWEEN those dates, but is there a more-convenient way to do this?
Why don't you consider using dateDiff as key function? As...
select dateDiff(wk, 0, getDate())
Returns a single integer for the whole week (6297 for '20200911') and :
select dateAdd(wk, dateDiff(wk, 0, getDate()), 0),
dateAdd(dd, 6, dateAdd(wk, dateDiff(wk, 0, getDate()), 0))
or
select dateAdd(wk, 6297, 0),
dateAdd(dd, 6, dateAdd(wk, 6297, 0))
gives you the 1st and last day of that week.
You can use DATEPART but instead of wk you can use the iso week. Then you don't have the problem with a week being split in 2. To be sure also use SET DATEFIRST to define exactly on which day the week starts.
SET DATEFIRST 1; --use monday as first day of the week
SELECT datepart(iso_week,'2021-01-01');
SELECT datepart(iso_week,'2021-01-03');
SELECT datepart(iso_week,'2021-01-04');
The other option is to create your own calendar table and join that to your daily table.
EDIT: for a week start on sunday
SET DATEFIRST 7;
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2020-12-27'),'2020-12-27' ) )
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2020-12-28'),'2020-12-28' ) )
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2021-01-01'),'2021-01-01' ) )
SELECT DATEPART(WEEK, DATEADD( DAY, 1-DATEPART(WEEKDAY,'2021-01-02'),'2021-01-02' ) )

Produce data extracts using day field for the Friday before the weekend

Using TSQL on SQL Server...
I need to produce extracts that use a pay day column in a database that only holds the day number, for example 26 to produce extracts for the 26th day of the month with a twist if that pay day falls on a weekend then the data for that extract should be extracted the Friday before the weekend.
Has anybody attempted this and able to offer some ways of achieving this through TSQL?
Thanks
You have said in today's comment above that you are assuming the current month.
First turn your payday day number into a proper date:
select dateadd(month,((year(getdate())-1900)*12)+month(getdate())-1,payday-1)
as paydate
and then use a case statement against it:
case datename(weekday,paydate)
when 'Saturday' then dateadd(day,-1,paydate)
when 'Sunday' then dateadd(day,-2,paydate)
else paydate
end as paydateadjust
(Obviously these will need rewriting into a proper SQL statement. Date formula borrowed from Michael Valentine Jones' super useful SQL Server date function.)
I'm assuming you have the month and year available too, in which case you can construct a real date, and get the day of week from it as a 1-based number starting at Sunday. So, 6 equals Friday. This will produce 5 for today, as Thursday = 5
SELECT DATEPART(dw, DATEFROMPARTS(2018, 07, 26)) AS [DayOfWeek]
EDIT:
I'll make another assumption, this time that this is somehow possible, like it's always run for the current month. This is a bit dodgy as it all falls apart if it's run too early or too late, but at least it's achievable.
SELECT DATEPART(dw, DATEFROMPARTS(
DATEPART(YEAR, GETDATE()),
DATEPART(MONTH, GETDATE()),
26)) AS [DayOfWeekThisMonth]
EDIT 2:
OK, with the understanding we are working on this month, we can do this:
DECLARE #PayDayNumber INT = 29; -- Replace this with a SELECT to get your value
SELECT CASE(DATEPART(dw, DATEFROMPARTS(DATEPART(YEAR, GETDATE()), DATEPART(MONTH, GETDATE()), #PayDayNumber)))
WHEN 1 THEN #PayDayNumber - 2
WHEN 7 THEN #PayDayNumber - 1
ELSE #PayDayNumber
END AS [WeekendSafePayDay]
For this month (August 2018) the 29th will return 29th. You can change DATEPART(MONTH, GETDATE()) for 9 to test September, which will return 28 because 29th September is a Saturday, or change it to 7 to test July, which will return 27 because 29th July is a Sunday.

DATEADD(day, -7, GETDATE()) - Does it take time into account?

I am writing a SQL query in Aginity through Amazon Redshift to extract the last 7 days of data. The Date column which I am calling is in the variable type:
DATE
An example output is this:
5/30/2017 0:00
When I call the below function, does it matter what time of day I run this query or will it always take the full day's worth of data?
WHERE Date >= DATEADD(day,-7, GETDATE())
Yes, this includes the current time component when subtracting 7 days. To get rid of that, convert to a date:
WHERE Date >= CAST(DATEADD(day, -7, GETDATE()) as DATE)

Get data between two times for the last 30 days

I have a query to pull data from the last 30 days and I am using this function
DATEADD(day, -30, GETDATE())
I am getting the data but it looks like it is missing some Like when I look at the data for specific date it doesn't include all the 24 hours data I am missing some. I need the data to include the 24 hours data for every day for the last 30 days.
select
*
from
Travel R
where
R.s9_date > CONVERT(date, DATEADD(day, -30, GETDATE()))
order by
R.s9_date
Thanks
GETDATE() returns a datetime which includes the hours, minutes, seconds, etc. Therefore when you subtract 30 days from that, the subtracted value will also have the time part.
Assuming you're using SQL Server 2008 or above, you can convert the datetime to a date by wrapping the DATEADD function with a CONVERT function:
CONVERT(date, DATEADD(day, -30, GETDATE()))
I believe CAST was introduced in SQL Server 2005
select
*
from
Travel R
where
R.s9_date > CAST(DATEADD(DAY, -30, GETDATE()) AS DATE)
order by
R.s9_date

How to add days to the current date?

I am trying to add days to the current date and it's working fine but when I add 360 days to the current date it gives me wrong value.
eg: Current Date is 11/04/2014
And I am adding 360 Days to it, it should give me 11/04/2015, but it is showing the same date 11/04/2014. the year is not changing.
Here is my code:
select dateadd(dd,360,getdate())
Just do-
Select (Getdate()+360) As MyDate
There is no need to use dateadd function for adding or subtracting days from a given date. For adding years, months, hours you need the dateadd function.
select dateadd(dd,360,getdate()) will give you correct date as shown below:
2017-09-30 15:40:37.260
I just ran the query and checked:
Dateadd(datepart,number,date)
You should use it like this:
select DATEADD(day,360,getdate())
Then you will find the same date but different year.
From the SQL Server 2017 official documentation:
SELECT DATEADD(day, 360, GETDATE());
If you would like to remove the time part of the GETDATE function, you can do:
SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
can try this
select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result
Two or three ways (depends what you want), say we are at Current Date is
(in tsql code) -
DECLARE #myCurrentDate datetime = '11Apr2014 10:02:25 AM'
(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)
SELECT #myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.
SELECT DateADD(DAY, 365, #myCurrentDate) or DateADD(dd, 365, #myCurrentDate)
will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE #myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).
So what I think you meant was
SELECT DateADD(year, 1, #myCurrentDate)
which gives 2015-04-11 10:02:25.000.
or better yet
SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, #myCurrentDate), 0))
which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?
This will give total number of days including today in the current month.
select day(getDate())
Add Days in Date in SQL
DECLARE #NEWDOB DATE=null
SET #NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)
SELECT DateAdd(5,day(getdate()) this is for adding 5 days to current days.
for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query

Resources