Datediff function between a date column and current date? - sql

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

Related

SQL Server 3 month from now

I need a SQL select statement to retrieve all employees that their enddate contract will end three month from now and only three month not more or less
It depends what you mean by 3 months from now. If you mean on that exact date, then:
WHERE my_date_column = cast(dateadd(month, 3, getdate()) as date)
Note the cast to date to remove the time component. This is ambiguous and under some circumstances might miss employees or count them twice.
If you want employees whose contract ends in the 3rd month from today, then use:
WHERE DATEDIFF(month, getdate(), my_date_column) = 3
So, if this is January, this will return employees whose contract ends any time in April.
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, +90, GETDATE())
OR
SELECT *
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, +3, GETDATE())
OR
SELECT *
FROM TABLE_NAME
WHERE DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

how to get records who is reaching todays date

I want to get records who are about reach todays date with in 2 days ProjectEnddt. i want to show Projects who are going to end with in 2 days. want to show 2 days before.
Query
SELECT ProjectEndDt
, ProjectRenewalDt
, ProjectUpgradeDt
FROM tbl_project
WHERE CONVERT(VARCHAR(10), DATEADD(DAY, 2, ProjectEndDt)) >= CONVERT(VARCHAR(10), GETDATE());
Try this:
SELECT ProjectEndDt
,ProjectRenewalDt
,ProjectUpgradeDt
FROM tbl_project
WHERE CONVERT(DATE,[ProjectEndDt]) < DATEADD(DAY, 3,CONVERT(DATE,GETDATE()))
Try this:
SELECT ProjectEndDt
,ProjectRenewalDt
,ProjectUpgradeDt
FROM tbl_project
WHERE CAST(ProjectEndDt AS DATE) < CAST(DATEADD(DAY, 3, GETDATE()) AS DATE)

select month and year from Date of birth IN sql

i have table with DOB column ('2012-05-29 00:00:00.000') and few other fields , i need to select the data for DOB between 6 months to 6 Years. I tried using the below SQL but this is not giving me the right data. any help will be appreciated.
select * from dbo.xyz
where ( FLOOR(DATEDIFF(MONTH, birth_date , GETDATE()) % 12) >=6
AND FLOOR(DATEDIFF(DAY, birth_date , GETDATE()) / 365.25) <= 6
)
When using dates, the advice is to use functions only on the non-column values. In other words, modify getdate(), not birth_date:
select *
from dbo.xyz
where birth_date between dateadd(year, -6, getdate()) and dateadd(month, -6, getdate())
This has two advantages. First, it makes the where clause "sargable", which means an index can be used on the comparison. More importantly, the alternative of using datediff() doesn't quite work as expected. datediff() counts the number of calendar boundaries between two values. So, 2014-12-31 and 2015-01-01 are one day apart, one month apart, and even one year apart.
Try this
select * from dbo.xyz
where DATEDIFF(MONTH, birth_date , GETDATE()) between 6 and 72
Here is another option that will allow indexing on birthdate.
select *
from dbo.xyz
where birthdate > DATEADD(YEAR, -6, GETDATE())
and birthdate < DATEADD(MONTH, -6, 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.

SQL Last 6 Months

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'))