SQL Last 6 Months - sql

I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
where datetime_column > DATEADD(m, -6, current_timestamp)
But how to extend this option if I want to return latest month beginning with first day of the month? E.g. I run this condition in the middle of month (14/6/2000), the latest row is set to 14/1/2000, but i would like to return it as 1/1/2000. Any advice?
I tried some subqueries (max function of datetime including month function) but with no success.

For MS SQL Server, you can use:
where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)

In SQL Server
where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)
SQLFiddle demo
In MySQL
where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month
SQLFiddle demo

Try this one
where datediff(month, datetime_column, getdate()) <= 6
To exclude or filter out future dates
where datediff(month, datetime_column, getdate()) between 0 and 6
This part datediff(month, datetime_column, getdate()) will get the month difference in number of current date and Datetime_Column and will return Rows like:
Result 1 2 3 4 5 6 7 8 9
10
This is Our final condition to get last 6 months data
where result <= 6

.... where yourdate_column > DATE_SUB(now(), INTERVAL 6 MONTH)

select *
from tbl1
where
datetime_column >=
DATEADD(m, -6, convert(date, convert(varchar(6), getdate(),112) + '01'))

Related

Datediff function between a date column and current date?

How can I correctly calculate the difference in days or years between a date column and the current date?
typically would use
where date_diff('day, date_column1, date_column2) as difference
So what I need is if the difference between the date column and todays date is 3 days then 3 or 3 years then 3.
Thanks
In SQL SERVER, you can use the following query (replace the date with your field):
SELECT CASE WHEN datediff(year, '20120303', getdate()) > 1
THEN datediff(year, '20120303', getdate())
ELSE datediff(day, '20120303', getdate()) END AS Diff
Using your sample:
SELECT CASE WHEN datediff(year, date_column, getdate()) > 1
THEN datediff(year, date_column, getdate())
ELSE datediff(day, date_column, getdate()) END AS Diff

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.

In sqlserver how to find last before week data?

I am trying the below query, but it's output comes last 2 weeks data, but I need only last before week data only.
select * from tablename where createddate>=DATEADD(WEEK,-2, GETDATE()) ;
Just add another condition to your WHERE clause to restrict to earlier than the week before last:
SELECT * FROM tablename
WHERE createddate >= DATEADD(WEEK,-2, GETDATE()) AND
createddate < DATEADD(WEEK,-1, GETDATE())
From one your comments I found that the week you are talking about starts from Friday, so you need to add up those gap days into your condition
SELECT * FROM tablename
WHERE createddate >= DATEADD(ww, DATEDIFF(ww, 4 ,DATEADD(WEEK, -1, GETDATE())), 4)
AND createddate < DATEADD(ww, DATEDIFF(ww, 4 ,DATEADD(WEEK, 0, GETDATE())), 4)
this code is currect answer for my quation,
select * from dbo_OrdersCompleteView1 where S2_DateTimeOrederLines between DATEADD(WEEK,-2, GETDATE()) and DATEADD(WEEK,-1,GETDATE());

How can I get the last 12 months from the current date PLUS extra days till 1st of the last month retrieved

Getting the last 12 months from a specific date is easy and can be retrieved by the following command in SQL-server. Its answer is 2014-08-17.
select Dateadd(Month, -12, '2015-08-17')
What I want is to get the last 12 months but ending at 2014-08-01 (in the above case) instead of any where in the middle of the month.
SELECT dateadd(month,datediff(month,0,getdate())-12,0)
Result is
-----------------------
2014-08-01 00:00:00.000
So the where clause should be
WHERE datecol >=dateadd(month,datediff(month,0,getdate())-12,0)
to get all data starting from jan 01 of last year's same month
Using DATEADD and DATEDIFF:
DECLARE #ThisDate DATE = '20150817'
SELECT DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', #ThisDate), '19000101'))
For more common date routines, see this article by Lynn Pettis.
To use in your WHERE clause:
DECLARE #ThisDate DATE = '20150817'
SELECT *
FROM <your_table>
WHERE
<date_column> >= DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', #ThisDate), '19000101'))
If you want all the records since the first day of the current month last year, then you can use:
where <somedate> >= dateadd(day, 1 - day(dateadd(month, -12, getdate()),
dateadd(month, -12, getdate()))
For all days except Feb 29th, you can use the simpler:
where <somedate> >= dateadd(day, 1 - day(getdate()),
dateadd(month, -12, getdate))

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.