DATEADD to return data in the last 3 months but I want full month of data - sql

So my query aims to grab all data in the last 3 months, but only returns data when it is a full month.
I have tried:
WHERE Created_Date > DATEADD(MONTH, -3, GETDATE())
or
WHERE Created_Date > DATEADD(DAY, -90, GETDATE())
Both ways return the data in the last 3 months starting from current date. But the thing is, since my query wants to get aggregated data, so if today is 8th Aug, 3 months dating back means May has not got the full month of data (from 1st to 31st), so the aggregated data is not fully reported in the results. Does this make sense?
Is there any other way to return the full month data?
I know that we can use #startOfCurrentMonth like in here but this is 3 months we are aiming to get.

To get the days of the current month plus three full months back, simply subtract four months and get that month's last day. Then take any dates after that day.
WHERE created_date > EOMONTH(DATEADD(MONTH, -4, GETDATE()))
If created_date is a misnomer and contains datetimes instead of dates, add a day and include that:
WHERE created_date >= DATEADD(DAY, 1, EOMONTH(GETDATE(), -4)))

Related

Pull data from the third week back from this week? [duplicate]

This question already has answers here:
Query to get content older than 3 weeks
(3 answers)
Closed 2 years ago.
This week is the week of 12/28/20. I want to pull data from the third week back of whatever the current week is. So if I run my query today I want it to pull data for the week of 12/7 only. I'm trying to do this and its not returning any results. Any ideas? Thank you
WHERE date = DATEADD(week, -3, GETDATE())
I prefer the following which:
Allows you to use the Date column without calling a function on it. This is important for sargability i.e. the ability for SQL Server to use an index on the Date column. Although in my testing a cast to date still did you use the index, its best practice to avoid functions calls on the columns in where clauses.
Avoids the use of between, which I always have to take a moment to think about because its >= the first condition and <= the second condition. So its easy to get the logic wrong and include 8 days instead of 7. Instead I always use an explicit compare so its obvious what the logic is.
Note the >= and < now rather than <=.
where [Date] >= convert(date,dateadd(week, -3, current_timestamp))
and [Date] < convert(date,dateadd(week, -2, current_timestamp))
Now
Start Of Week (Inc)
End Of Week (Ex)
2020-12-29 20:07:16.373
2020-12-08
2020-12-15
And if you need it to start on your week start day then use:
where [Date] >= convert(date,dateadd(day, (-1*datepart(weekday,current_timestamp))+1, dateadd(week, -3, current_timestamp)))
and [Date] < convert(date,dateadd(day, (-1*datepart(weekday,current_timestamp))+1, dateadd(week, -2, current_timestamp)))
Now
Start Of Week (Inc)
End Of Week (Ex)
2020-12-29 20:07:16.373
2020-12-06
2020-12-13
That is only going to give you data that has a date that was three weeks ago from the current time to the nearest thousandth of a second. It's fairly unlikely that you have any data that exactly matches that.
What I expect you are after is data that is between three and two weeks ago which can be obtained like this:
WHERE date BETWEEN DATEADD(week, -3, GETDATE()) AND DATEADD(week, -2, GETDATE())
However if you run that half way through a day, it will only give you data from half way through the day three weeks ago until half way through the day two weeks ago. You probably want to go from midnight at the start and end of the day. This can be done by casting everything to the DATE type, which has the effect of discarding the time, like this:
WHERE CAST(date AS DATE) >= CAST(DATEADD(week, -3, GETDATE()) AS DATE) AND CAST(date AS DATE) < CAST(DATEADD(week, -2, GETDATE()) AS DATE)
It is also possible that you want to have the weeks always start on the same day of the week. This can be done using the DATEPART function.
WHERE DATEPART(week, date) = DATEPART(week, DATEADD(week, -3, GETDATE())) AND DATEPART(year, date) = DATEPART(year, DATEADD(week, -3, GETDATE()))
Depending upon what you want and how your database is set up this last option may require setting the SET DATEFIRST setting to get the correct day to start the week on. For example to start the week on Mondays use:
SET DATEFIRST 1;

Add column for Fiscal Week Number in an SQL SELECT Statement

Tried to add a custom Fiscal Week column to my DimDate table in a query.
Some background: the fiscal year always begins on 02-01 [February 1]. My DimDate tables earliest date goes to January 01, 2008 [01-01-2008]. I looked at previous posts and tried in the code below, except I got 0 for the Week Number for 02-01-2008 and 02-02-2008.
Datediff(wk, CONVERT(DATE, '2008-02-01'), CONVERT(DATE, dbo.DIMDATE.DATE_VALUE)) AS 'FiscalWeek',
If I followed you correctly, you can just offset the date by 1 month:
datepart(wk, dateadd(month, -1, datevalue)) as fiscal_week
Depending on your actual requirement, you might want to try isowk as well.

Data Preparation End OF Every Month - Moving Over 12 Months

I have data prep procedure in SQL. I want to have data preparation at the end of every month
Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.
So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.
I tried this, however, this does not give automation. Its sort of manual running end of every month
select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
into #AnalysisWindow --create temporary table #AnalysisWindow
I also tried the following, however, I’m not sure if it does for the whole month or just one day?
SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1, CAST(GETDATE() AS DATE))
Could someone pls help me/give me some suggestions.
Thanks in advance
If you want the last day of the current month, use eomonth():
WHERE DATE = CONVERT(date, EOMONTH(GETDATE()))
Note: This assumes that the date column has no time component. If that is the case:
WHERE CONVERT(date, DATE) = CONVERT(date, EOMONTH(GETDATE()))
SQL Server will still use an index (if available) even for this type of conversion.
EDIT:
To get the current months data, one method is:
WHERE DATE <= CONVERT(date, EOMONTH(GETDATE())) AND
DATE > CONVERT(date, EOMONTH(GETDATE(), -1))
The second argument to EOMONTH() is a months offset.
You can also try:
where getdate() <= EOMONTH(GETDATE()) AND
getdate() > DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
Instead of getdate(), you can use your date column.

How to subtract one month from a Date Column

I know about Dateadd and datediff, but I cannot find any information how to use these functions on an actual date column rather than something like today's date with SQL Server.
Say I have the following Column
Dated
06/30/2015
07/31/2015
Now I want to add the following derived column that subtracts one month from every row in the Dated column.
Dated Subtracted
06/30/2015 05/31/2015
07/31/2015 06/30/2015
Thank you
The short answer: I suspect this is what you want:
dateadd(day, -datepart(day, Dated), Dated)
However, if you want "regular" subtract one month behavior in tandem with sticking to the end of month, having June 30 fall back to May 31 is slightly trickier. There's a discrepancy between the title or your question and the example where it appears you want the final day of month to stay anchored. It would be helpful for you to clarify this.
dateadd(month, -1, ...) doesn't handle that when the previous month has more days than the starting month although it works the other way around. If that's truly what you need I think this should handle it:
case
when datediff(month, Dated, dateadd(day, 1, Dated)) = 1
then dateadd(day, -datepart(day, Dated), Dated)
else dateadd(month, -1, Dated)
end
There's also a flavor of several date functions in that expression and a sense of how this date stuff can get complicated. The condition in the when looks to see if Dated is the last day of the month by checking that the following day is in a different calendar month. If so we extract the day of month and subtract that many days to jump back to the last day of the previous month. (Months start at one not zero. So for example, counting backward 17 days from the 17th lands in the month before.) Otherwise it uses regular dateadd(month, -1, ...) calculations to jump backward to the same day of month.
Of course if all your dates fall on the end of the month then this simple version will be adequate by itself because it always returns the last day of the previous month (regardless of where it falls in the starting month):
dateadd(day, -datepart(day, Dated), Dated) /* refer back to the top */
dateadd(day, -day(Dated), Dated) /* same thing */
And just for fun and practice with date expressions, another approach is that you could start on a known month with 31 days and calculate relative to that:
dateadd(month, datediff(month, '20151231', Dated) - 1, '20151231')
This finds the number of months between your date and a reference date. It works for all dates since it doesn't matter whether the difference is positive or negative. So then subtracting one from that difference and adding that many months to the reference point is the result you want.
People will come up with some pretty crazy stuff and I'm often amazed (for differing reasons) at some of the variations I see. chancrovsky's answer is a good example for closer examination:
dateadd(month, datediff(month, -1, Dated) - 1, -1)
It relies on the fact that date -1, when treated as implicitly converted to datetime, is the day before January 1, 1900, which does happen to be a month of 31 days as required. (Note that the - 1 in the middle is regular arithmetic and not a date value.) I think most people would advise you to be careful with that one as I'm not sure that it is guaranteed to be portable when Microsoft deprecates features in the future.
Why don't you just get the last day of the previous month? If this solve your problem, here's the sql server syntax, just replace the variable #yourDate with your column name.
DECLARE #yourDate DATE = '20160229'
select DATEADD(MONTH, DATEDIFF(MONTH, -1, #yourDate)-1, -1)
This also works if you're looking to find dates exactly 6 months behind.
Example:
DATEADD(DAY, DATEDIFF(DAY, -1, dates)-184, -31)

Get Week Before Last

Hi I am trying to pull data which will excluded the previous 2 weeks and include the 2 weeks beofre that.
so for example if today is the 31st of the month i want to exclude all data between the 15th and 31st and want to see only the 1st to the 15th
AND E.EventCreatedDateD between DATEADD(day,-14,GETDATE()) AND DATEADD(day,-31,GETDATE())
You are getting 0 values from your statement because the dates are backwards. Put the earlier date first:
AND E.EventCreatedDateD between DATEADD(day, -31, GETDATE()) AND DATEADD(day, -14, GETDATE())
The order of the expressions for the between is important. The lower value always needs to be first and the higher value second.