Datediff GETDATE Add - sql

In this type of code,
AND Orders.ShipDate >= DATEADD(Day, Datediff(Day,0, GetDate() -6), 0)
It supposed to pull records with the date 6 days ago, until today. How can I make it pull records from 7 days ago until yesterday?
I know changing -6 to -7 will pull records from 7 days ago, but which variable is the end of the date span so I can change it to -1?

It's not a date span.
The condition you have there is really only one condition: greater than. The right side of the greater than is 6 days ago, so your condition matches any date that is later than the date six days ago. In other words, it doesn't stop at Today; it includes tomorrow, next week, and next year, too.
AND ( Orders.ShipDate >= DATEADD(Day, Datediff(Day,0, GetDate() -7), 0)
AND Orders.ShipDate < DATEADD(Day, Datediff(Day,0, GetDate()), 0) )
That's what you really want. It matches dates which are later than midnight of the day 7 days ago, and dates which are before midnight today (which is any time yesterday).

The "end of the date span" isn't in your query.
Change your code to:
AND (Orders.ShipDate BETWEEN DATEADD(Day, -1, GetDate()) AND DATEADD(Day, -7, GetDate()))

This should work too and it eliminates the needless addition of 0 days:
select *,DATEDIFF(Day, orders.ShipDate, GETDATE()) AS DAYS_SINCE_TODAY
from Orders
where DATEDIFF(Day, orders.ShipDate, GETDATE()) >= 1 AND --This many days since today
DATEDIFF(Day, orders.ShipDate, GETDATE()) <= 7 --Going back this many days

I like the BETWEEN function. This may be a different flavor of SQL than you are using, but this is what I use.
BETWEEN dateadd(second, 0, dateadd(dd,datediff(dd,7,getdate()),0)) AND dateadd(second,-1, dateadd(dd,datediff(dd,0,getdate()),0))

Related

Pulling Data from six months prior to current date not working

I'm trying to pull data submitted 6 months from the current date. Every day this report will run and I want it to choose the data automatically. I've entered this code and nothing is coming up. There isn't an error, it's almost as if nothing was entered on the date.
L.Open_Date = DATEADD(month, -6, GETDATE())
However, if I have confirmed there was data entered in on the date 6 months ago. I changed the code to
L.Open_Date >= DATEADD(month, -6, GETDATE())
and this code works. It brings back everything submitted 6 months prior to the current date.
Is there a way to get the 6 months ago data only to pull up?
Presumably, you want:
L.Open_Date = DATEADD(month, -6, CAST(GETDATE() AS DATE))
This gives you 6 months back without the time component (which getdate() otherwise returns). This would work if Open_Date is a date itself. If it has a time component that you want to ignore, then this would be:
CAST(L.Open_Date AS DATE) = DATEADD(month, -6, CAST(GETDATE() AS DATE))
Or the longer, but SARGable:
L.Open_Date >= DATEADD(month, -6, CAST(GETDATE() AS DATE))
AND L.OPen_DAte >= DATEADD(day, 1, DATEADD(month, -6, CAST(GETDATE() AS DATE)))

Looking for a getdate/dateadd statement to do 1 year and +/- 15 days

-- This is my current code which will allow for me to see all our work orders that have been submitted within the past week, and lets me know if any of the same work orders have appear 6 months ago.
SELECT
A.tagnumber,
count(*) AS CountTotal
FROM
v_workorder A
WHERE
--Date range Within Today and 6 months ago
wo_requestDate BETWEEN DATEADD(month, -6, GETDATE()) AND GETDATE()
AND
EXISTS
( -- Date range Within Today and 7 days ago
select
tagnumber
FROM
v_workorder
WHERE
wo_requestDate BETWEEN DATEADD(DAY,-7,GETDATE()) AND GETDATE()
)
AND
A.wc_description = 'Corrective'
AND
A.itemtype_name = 'Building'
GROUP BY A.tagnumber
ORDER BY CountTotal DESC
--However, Now I would like for my first variable of the getdate/adddate. To check back 1 year ago, +/- 15 days. So essentially 1 year and 15 days back instead of 6 months.
For past 1 year +/- 15 Days
SELECT A.tagnumber, count(*) AS CountTotal
FROM v_workorder A
WHERE wo_requestDate BETWEEN DATEADD(day, -15, DATEADD(year, -1, GETDATE())) AND DATEADD(day, 15, DATEADD(year, -1, GETDATE()))
AND
EXISTS ( select tagnumber FROM v_workorder WHERE wo_requestDate BETWEEN DATEADD(DAY,-7,GETDATE()) AND GETDATE() )
AND
A.wc_description = 'Corrective' AND A.itemtype_name = 'Building'
GROUP BY A.tagnumber
ORDER BY CountTotal DESC
For 1 year
SELECT ...
FROM ...
WHERE wo_requestDate BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE()
AND...;
For 15 Days
SELECT ...
FROM ...
WHERE wo_requestDate BETWEEN DATEADD(day, -15, GETDATE()) AND GETDATE()
AND...;
Other possible options of DATEADD()
year
quarter
month
dayofyear
day
week
weekday
hour
minute
second
millisecond
See more here.
.
To eliminate issues with the time component of datetime:
CAST(GETDATE() AS DATE
Find the date from a year ago:
SELECT DATEADD(YEAR, -1, CAST(GETDATE() AS DATE));
From there, subtract 15 days and add 15 days in your end points.
...
WHERE
wo_requestDate >= DATEADD(DAY, -15, DATEADD(YEAR, -1, CAST(GETDATE() AS DATE)))
AND
wo_requestDate < DATEADD(DAY, 15, DATEADD(YEAR, -1, CAST(GETDATE() AS DATE)))
I prefer >= and < to BETWEEN, especially with dates, just to avoid any ambiguity with the time component, so you may want to add 16 days to the last parameter if you want the range to include the 15th day out.

Function to go back 2 years, first day of last month

I'm hoping to find a solution for this to automate a report I have. Basically what I'm trying to accomplish here is grabbing a date (first day of previous month, two years ago through last day of previous month current year).
So the date span if running this month would look like this: between 4/1/2013 and 3/31/2015
I have found code to get the date two years ago but I'm not able to also incorporate the month functions... Any help is very much appreciated!
For year I'm using this:
SELECT CONVERT(VARCHAR(25),DATEADD(year,-2,GETDATE()),101)
First day of previous month 2 years ago:
SELECT CONVERT(DATE,dateadd(day, -1, dateadd(day, 1 - day(GETDATE()), GETDATE())))
Last day of last month:
SELECT CONVERT(DATE,DATEADD(month, DATEDIFF(month, 0, DATEADD(year,-2,GETDATE())), 0))
Then just do whatever logic you need with them
Your where clause can look something like this:
where date >= cast(dateadd(year, -2,
dateadd(month, -1, getdate() - day(getdate()) + 1)
) as date) and
date < cast(getdate() - day(getdate()) + 1 as date)
This makes use of the handy convenience that subtracting/adding a number to a datetime is the same as adding a date. The start date says: get the first day of the month, then subtract one month, then subtract two years. This could have been done as dateadd(month, -25, . . .), but I think separating the logic is clearer.
This gives you two dates you are looking for:
SELECT
CAST((DATEADD(yy, -2, DATEADD(d, -1 * DATEPART(dd, getdate()) + 1 , GETDATE() ))) as date) as yourTwoYearsAgoDate,
CAST((DATEADD(d, -1 * DATEPART(dd, GETDATE()), GETDATE())) as date) as yourEndOfLastMonthDate
Given a reference date (e.g. "today"),
declare #today date = '23 April 2015'
The 1st of the month is computed by subtracting 1 less than the day number of the current month:
select first_of_current_month = dateadd(day,1-day(#today),#today)
The last day of the previous month is day 0 of the current month, so to get the last day of the previous month, just subtract the current day number:
select last_of_previous_month = dateadd(day,-day(#today),#today)
Moving two years back is easy:
select two_years_back = dateadd(year,-2, #today )
Putting it all together, this should do you:
declare #today date = '23 April 2015'
select *
first_day_of_current_month = dateadd(day,1-day(#today),#today),
last_day_of_previous_month = dateadd(day, -day(#today),#today) ,
date_from = dateadd(year,-2, dateadd(day,1-day(#today),#today) ) ,
date_thru = dateadd(day, -day(#today),#today)
yielding the expected results:
first_day_of_current_month: 2015-04-01
last_day_of_previous_month: 2015-03-31
date_from : 2013-04-01
date_thru : 2015-03-31
So you should be able to say something like this:
select *
from foo t
where t.transaction_date between dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and dateadd(day, -day(#today),#today)
If you have to deal with datetime values rather than date, its easier to not use between and say something like this:
declare #today date = current_timestamp -- get the current date without a time component
select *
from foo t
where t.transaction_date >= dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and t.transaction_date < dateadd(year, 0, dateadd(day, -day(#today),#today)
[superfluous addition of 0 years added for clarity]

Keyword for "Last Month" in SQL Server 2008

I have a query (pasted below), and I would like to make it so that people don't need to update the completed date range. I would like for it to automatically just get results from last month. So if it is run in February, for example, it will give me results for all completed items that meet my criteria for January. Can anyone think of a way to do that?
select External_ID__c,
Ewrk_Tracking_Number__c,
PIF_Branch_Name,
Distribution_Branch_Name,
Transaction_Type__C,
submitter_date__c, Completed_Date__C,
COUNT(External_ID__c)
from Business_Solutions_D.dbo.Reporting_SalesForce_AspireBaseData
where PIF_Branch_Code = 977
and Completed_Date__C >= '2015-01-01'
and Completed_Date__C < '2015-02-01'
and Delete_Flag__C = 'FALSE'
group by External_ID__c,
Ewrk_Tracking_Number__c,
PIF_Branch_Name,
Distribution_Branch_Name,
Transaction_Type__C,
submitter_date__c,
Completed_Date__C
There is no "keyword" for last month. You have to put that in your predicates.
Here is an example of how to get some date values for this.
select dateadd(MONTH, datediff(MONTH, 0, GETDATE()), 0) as BeginningOfThisMonth
select dateadd(MONTH, datediff(MONTH, 0, GETDATE()) - 1, 0) as BeginningOfPreviousMonth
If you want to see a number of other date routines here is an excellent blog post with quite a few of them. http://www.sqlservercentral.com/blogs/lynnpettis/2009/03/25/some-common-date-routines/
If you mean the last month prior to this one, you can do it in two steps: first, find the first day of the current month
#firstDayOfThisMonth = DATEADD(day, DAY(GETDATE())-1, GETDATE())
then subtract one month:
#firstDayOfLastMonth = DATEADD(month, -1, #firstDayOfThisMonth)
Then your query would be:
and Completed_Date__C >= #firstDayOfLastMonth
and Completed_Date__C < #firstDayOfThisMonth
Another way would be to query where the difference (in months) between Completed_Date__C and the current date is 1:
and DATEDIFF(Completed_Date__C, GETDATE()) = 1
You can do this with date arithmetic. One trick to get the first date of the month is to subtract the current day of the month from the date and add one day. SQL Server allows you to do this with + and - instead of dateadd(), on a datetime value. Of course, you need to remove the time component as well (using cast( as date)).
The logic looks like this for the current month:
where Completed_Date__C >= cast(getdate() - day(getdate()) + 1 as date) and
Completed_Date__C < dateadd(month, 1, cast(getdate() - day(getdate()) + 1 as date))
And like this for the previous month:
where Completed_Date__C >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
Completed_Date__C < cast(getdate() - day(getdate()) + 1 as date)
This has the nice property that it is a sargeable as your original code, so it will take advantage of an index on the column, if appropriate.
You just need to have it do some date math to calculate it.
--Go to last day of prev month - 'Day' to account for varying month day counts
and Completed_Date__C >= GETDATE() - DATEPART(DAY, GETDATE()) - DATEPART(DAY, GETDATE() - DATEPART(DAY, GETDATE())) + 1
and Completed_Date__C < GETDATE() - DATEPART(DAY, GETDATE()) + 1
When you do additions on DateTimes + integer it assumes it day based addition.

Select all records 'younger' than 7 days

I want to select all the records from [Orders] that have a [Submissiondate] less than 7 days.
I'm completely stumped. This is the query I'm executing:
SELECT * FROM [Orders] WHERE ([SubmissionDate] < #SubmissionDate)
Doesn't work.
If you mean you want rows with SubmissionDate between #SubmissionDate and #SubmissionDate - 7 days, then this is how I would implement that in Transact-SQL:
WHERE [SubmissionDate] BETWEEN DATEADD(DAY, -7, #SubmissionDate)
AND #SubmissionDate
Note that BETWEEN implies >= and <=. If you need strict inequalities, make it something like this:
WHERE [SubmissionDate] > DATEADD(DAY, -7, #SubmissionDate)
AND [SubmissionDate] < #SubmissionDate
Assuming that the sql parameter #SubmissionDate is the date (and time) now. You could use the following query that will return those [Orders] submitted within the last 7 days:
SELECT * FROM [Orders] WHERE ([SubmissionDate] >= DATEADD(DD, -7, DATEADD(dd, 0, DATEDIFF(dd, 0, #SubmissionDate))))
Two important remarks to this solution:
Time 'part' is being removed from #SubmissionDate.
As there is no 'Date To' restriction, do includes the [Orders] submitted
'today' (until the time the query is being executed).
The following code is just to get the date 'part' only of a date-time (extracted from this other SO thread).
DATEADD(dd, 0, DATEDIFF(dd, 0, #SubmissionDate))
Try this
SELECT * FROM [Orders] WHERE [submission_date] < NOW() - INTERVAL 7
DAY;
You can also try this DATEDIFF
SELECT * FROM [Orders] WHERE datediff(d,SubmissionDate,GETDATE()) > 7
where GetDate() is today's date and the d is difference in days
select datediff(d,'2012/06/23',GETDATE())
should give you 7 because it's 7 days ago