0

I am trying to return the number of years someone has been a part of our team based on their join date. However i am getting a invalid minus operation error. The whole getdate() is not my friend so i am sure my syntax is wrong.

Can anyone lend some help?

SELECT 
  Profile.ID as 'ID', 
  dateadd(year, -profile.JOIN_DATE, getdate()) as 'Years with Org'
FROM  Profile
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
DerFox
  • 3
  • 2

4 Answers4

0

Looks like you're using T-SQL? If so, you should use DATEDIFF:

DATEDIFF(year, profile.JOIN_DATE, getdate())
Joseph M. Shunia
  • 310
  • 2
  • 10
0

MySQL Solution

Use the DATE_DIFF function

The DATEDIFF() function returns the time between two dates.

DATEDIFF(date1,date2)

http://www.w3schools.com/sql/func_datediff_mysql.asp

This method only takes the number of days difference. You need to convert to years by dividing by 365. To return an integer, use the FLOOR method.

In your case, it would look like this

SELECT 
  Profile.ID as 'ID', 
  (FLOOR(DATEDIFF(profile.JOIN_DATE, getdate()) / 365)) * -1 as 'Years with Org'
FROM  Profile

Here's an example fiddle I created

http://sqlfiddle.com/#!9/8dbb6/2/0

MsSQL / SQL Server solution

The DATEDIFF() function returns the time between two dates.

Syntax: DATEDIFF(datepart,startdate,enddate)

It's important to note here, that unlike it's MySql counterpart, the SQL Server version takes in three parameters. For your example, the code looks as follows

SELECT Profile.ID as 'ID', 
       DATEDIFF(YEAR,Profile.JoinDate,GETDATE()) as difference
FROM Profile

http://www.w3schools.com/sql/func_datediff.asp

Community
  • 1
  • 1
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
  • Is there a way to make that calculation down to the day ? For example of someone joined 6/1/2010 and today is 5/1/2016 it should return a 5. After or on 6/1/2016, it should return 6. – DerFox Apr 15 '16 at 20:35
0

Using the method from this answer, you can get your result with the following query :

SELECT 
  Profile.ID as 'ID', 
  YEAR(getdate()) - YEAR(profile.JOIN_DATE) - (DATE_FORMAT(getdate(), '%m%d') < DATE_FORMAT(profile.JOIN_DATE, '%m%d')) as 'Years with Org'
FROM  Profile
Community
  • 1
  • 1
Sam Bauwens
  • 1,317
  • 11
  • 18
0

If this is MS SQL:

    SELECT 
    Profile.ID as 'ID', 
    DATEDIFF(YEAR,Profile.JoinDate,GETDATE())
    FROM  Profile