Quantcast
Channel: MSDN Blogs
Viewing all articles
Browse latest Browse all 35736

TSQL - Solve it YOUR Way - Finding an Employee's Current Age Based on Birth Date

$
0
0

Introduction:

As part of the blog series TSQL - Solve it YOUR Way, today's topic will cover a question asked recently in the T-SQL MSDN forums where the solution, at first, seems extremely obvious.  However, as solutions were proposed and flaws were discovered with the proposals, the interesting nature of the problem was revealed.  As is the theme of the blog series, different solutions and explanations are provided from some of the most helpful and creative contributors in the TSQL MSDN forums.  This week, the contributors are Steven Wang, Olaf Helper, Tom Cooper, and Monica Rivera.

Topic:  Find an employee's age given their birth date.

A fun aspect to this question is the fact that we've all probably made these calculations hundreds of times in our minds throughout our lives as we hear birth dates in conversation so often.  The result is that it seems that the calculation should be so simple.  However, since SQL Server does not have an AGE() function that takes a datetime parameter and returns an age, we'll need to handle the logic and calculate it ourselves.  You can then store the result as a function in your SQL Server DBA/DB Developer toolbox and have the solution forever.  Three of the below solutions are somewhat similar using some variation of DATEFIFF(), but vary slightly in interesting ways, while one (Steven Wang's solution) takes on a completely new and interesting approach.  This is an outstanding example of why I've enjoyed collaborating with other SQL Server professional on this series to highlight different methods and solutions to a single problem.  The solutions show the true power of SQL Server as a programming language and also highlight the freedom that we as DBA's, DB developers, BI experts, etc. have in creating our solutions.  I hope you enjoy the solutions as much as I have.

Solution #1 - Provided by Olaf Helper 

 

Code Snippet
  1. DECLARE@reportDatedatetime;
  2. SET@reportDate=CONVERT(date,getdate());
  3.  
  4. ;WITH
  5.   birthdatesAS
  6.    (SELECT'Peter'ASName, {dN'1970-09-14'}ASBirthdateUNIONALL
  7.     SELECT'Bob'ASName, {dN'1970-11-27'}ASBirthdateUNIONALL
  8.     SELECT'Sabina'ASName, {dN'1970-11-28'}ASBirthdateUNIONALL
  9.     SELECT'Amy'ASName, {dN'1970-11-29'}ASBirthdateUNIONALL
  10.     SELECT'Jane'ASName,  {dN'1970-12-31'}ASBirthdateUNIONALL
  11.     SELECT'Julie'ASName, {dN'1971-12-31'}ASBirthdate)
  12. ,ageAS
  13.    (SELECT*
  14.           ,DATEDIFF(Year,Birthdate,@reportDate)ASAge
  15.           ,DATEADD(Year,DATEDIFF(Year,Birthdate,@reportDate),BirthDate)ASSwitchDate
  16.     FROMbirthdates)
  17.  
  18. SELECTage.Name
  19.       ,age.Birthdate
  20.       ,CASEWHENSwitchDate<=@reportDate
  21.             THENage
  22.             ELSEage- 1 ENDASAge
  23.       ,CASEWHENSwitchDate=@reportDate
  24.             THEN'Happy Birthday!!!'
  25.             ELSE''ENDASGratulation
  26. FROMage
  27. ORDERBYage.Birthdate;

 

Explanation of Olaf's solution:

The CTE "birthdates" creates sample data around the current date for reporting, plus some additional data to check the result.

The DateDiff with option "YEAR" function seems the first and obvious way to calculate the age, but it returns only the difference of the year part and doesn't account for the additional months.
For example:


SELECT DATEDIFF(YEAR, {d N'2000-01-01'}, {d N'2001-01-01'})
      ,DATEDIFF(YEAR, {d N'2000-01-01'}, {d N'2001-12-31'})

This returns 1 for both results, even though in the second example, the difference is "nearly" 2 years.

To solve this I still use the DateDiff function, then add the difference between the birth and the given date to the birthdate. In a CASE WHEN statement I compare the result with the given date and if it's higher, I subtract 1 to get the real age.

Solution #2 - Provided by Tom Cooper 

 

Code Snippet
  1. Declare@TestTable(EmpNamevarchar(40),BirthDatedate);
  2. Insert@Test(EmpName,BirthDate)Values
  3. ('30 Yrs old yesterday',DateAdd(day,-1,DateAdd(year,-30,GetDate()))),
  4. ('30 Yrs old today',DateAdd(year,-30,GetDate())),
  5. ('30 Yrs old tomorrow',DateAdd(day, 1,DateAdd(year,-30,GetDate())));
  6.  
  7. WithcteAs
  8. (SelectEmpName,BirthDate,DateDiff(year,BirthDate,GetDate())AsProvisionalAge
  9. From@Test)
  10. SelectEmpName,BirthDate,
  11.   ProvisionalAge-CaseWhenDateAdd(year,ProvisionalAge,BirthDate)>GetDate()Then 1 Else 0 EndAsAge
  12. Fromcte;

 

Explanation of Tom's solution:

This uses the fact that when you do a DATEDIFF() in years between birth date and the current date, the number you get is either the correct age or one year too large depending on whether or not the person has had a birthday in this year.  That can be determined by adding that number of years to the birth date and checking to see if you get a date greater than today.  If so, subtract 1. 

 

Solution #3 - Provided by Monica Rivera 

 

Code Snippet
  1. USEAdventureWorks
  2. GO
  3.  
  4. selectLoginID,BirthDate,
  5. CASEWHENDATEADD(YY,DATEDIFF(yy,BirthDate,GETDATE()),BirthDate)<GETDATE()THENDATEDIFF(yy,BirthDate,GETDATE())
  6. ELSEDATEDIFF(yy,BirthDate,GETDATE())-1 ENDASAGE
  7. fromHumanResources.Employee
  8. orderbyBirthDate

 

Explanation of Monica's solution:

There are two cases when calculating a person’s age:

1.  The birth date has already happened in the current year: the age is simply the current year minus the year of birth.
2.  The birth date has not yet happened in the current year: the age is equal to the current year minus the year of birth minus one.

A simple T-SQL expression to determine if the birth date has already happened in the current year is the following:

DATEADD(YY,DATEDIFF(yy,BirthDate,GETDATE()),BirthDate)<GETDATE()

This adds to the birth date the difference in years between to the birth date and today’s date. If this exceeds today’s date, then we are in case 2.

Plug it in to a case statement that describes the two cases above and you get the solution.

 

Solution #4 - Provided by Steven Wang 

 

Code Snippet
  1. --Extract some Test Data using the AdventureWorks sample database
  2. IfObject_ID('dbo.employee_birthdate')isnotNull
  3. Droptabledbo.employee_birthdate;
  4.   SELECT[NationalIDNumber]
  5.   ,[BirthDate]
  6. Intodbo.employee_birthdate
  7. FROM[HumanResources].[Employee]
  8. UnionAll
  9. Select-111111,'2000-02-29'
  10. UnionAll
  11. Select-222222,'2004-02-29'
  12. UnionAll
  13. Select-333333,Cast(Getdate()asDate);
  14. --Actual solution
  15. SELECT[NationalIDNumber],[BirthDate]
  16.   ,(Convert(Char(8),CURRENT_TIMESTAMP,112)- 0 -Convert(char(8),[BirthDate], 112))/ 10000 AsAge
  17. FROM[dbo].[employee_birthdate]
  18. OrderbyAge;

 

Explanation of Steven's solution:

  1. To calculate the age based on birth date needs to take account of 2 considerations: year difference and the date was born.
  2. Use the year difference as the base of the age calculation. If the current date is less than the date was born, then the age needs to minus 1 year.
  3. Inspired by the dimensional surrogate integer date key, we can use the date integer format to perform the calculation. For example, if a birthdate is ‘2001-09-30’, and current date is ‘2012-10-01’, then we can use the difference (20121001 – 20010930) / 10000 to get the age 11. As in T-SQL Integer / Integer is always Integer. In the same example, if the current date is ‘2012-09-29’, then the result (20120929 – 20010930) / 10000 will be 10.
  4. As we can’t directly convert the date format to integer value, I convert the date to char(8) first and use minus 0 to implicitly convert the char value to integer value.

Conclusion:

As you can see, all four of the above solutions provide the result we were looking for, but do so in creatively different styles.  Each of these solutions highlights the power and flexibility that SQL Server provides. I hope that you are able to learn a lot by trying out the problem yourself and then reading through the additional solutions.

Special thanks to Olaf, Tom, Monica, and Steven for their valuable forums contribution and for contributing to this series!

Hope that helps,
Sam Lester (MSFT)

Contributor Bios:

Steven Wang has worked with SQL server for more than 10 years. Steven is an active SQL server community participant and speaks at events such as TechEd, CodeCamp, SQL User Group etc.

Blog: www.MSBICOE.com | LinkedIn: Steven Wang | MSDN Profile: Steven Wang - Shangzhou

Tom Cooper began his programming career in 1968, began working with database software in 1977, and first worked with Microsoft SQL Server in 1994 (version 4.21).  He is now very happily retired.

Monica Rivera has been working with SQL Server for the past 10 years. She worked as a DBA before joining Microsoft, where she works as a tester for the SQL Server Enterprise & Tier 1 Manageability group.  She is very active in both the English and Spanish SQL Server MSDN forums.


Viewing all articles
Browse latest Browse all 35736

Trending Articles