SQL PRACTICE: SQL SERVER: DATEDIFF Function
Q11. Find the age of employees from the provided table using SQL?
N.B: I am using the following:
Database: MSSQL
SQL Dialect: T-SQL
Consider below table (Sql_data) as a source data.
select * from Sql_data;
-- Find the age of employees
select empid,
FirstName,
LastName,
DOB,
DATEDIFF(YY, DOB, GETDATE()) as Age
from Sql_data;
Syntax:
DATEDIFF(datepart, Date1, Date2)
Parameters:
datepart - Used to get the time difference between the two dates. It can be Year(YY, YYYY), Quarter(QQ, Q), month(MM,M), day(DD, D), …..etc.... In our case, we want to return the age in Year.
Date1 - the first date in operation. In our case, we are going to use the DOB column.
Date2 - the second date we want to compare to the first date. In our case, we are going to use GETDATE() to get the current year.
DATEDIFF(YY, DOB, GETDATE()) as Age
Comments
Post a Comment