Calculating age at time of an event in SQL [duplicate] - sql

This question already has answers here:
How to calculate age (in years) based on Date of Birth and getDate()
(40 answers)
Closed 2 years ago.
What is the best way to calculate age based on an event? I'm trying to look for individuals based on their age when an event took place? I'm relative new to SQL and the dates functions, I can't wrap my head around.
Example:
ID Name Age DOB AdmitDate
1234 John Smith 61 1960-07-15 2019-10-22
How can I can calculate whose age was 59 at the time of admit date?

DATEDIFF provides the function to do this.
e.g.
SELECT DATEDIFF ( yy , '1960-07-15' , '2019-10-22' )

Select * from yourtable
where DATEDIFF( year , CAST(DOB AS datetime), CAST(AdmitDate AS datetime)) >= 59
Try this

Related

get age in years for month of july [duplicate]

This question already has answers here:
How to calculate age (in years) based on Date of Birth and getDate()
(40 answers)
Closed 3 months ago.
I have a table that stores the date of birth of patients in DateTime format(2022-06-22).
How can I get the age in years for people born in July?
I have tried the below:
select sFirstName,
sLastName,
dDateOfBirth,
DATEDIFF(yy,dDateOfBirth,GETDATE()) as Age,
ifkMedicalAidID
from Patients
where DATEDIFF(month,dDateOfBirth,GETDATE()) between 5 and 5
Although I get only all the records for July(which is correct) all the ages are 0, I see the problem with the above query but I don't have the SQL knowledge to resolve it...
SELECT
FLOOR((DATEDIFF(DAY,0,GETDATE()) - DATEDIFF(DAY,0,dDateOfBirth)) / 365.2425) AS AgeYears
this did the trick thanks John
select sFirstName,
sLastName,
dDateOfBirth,
DATEDIFF(yy,dDateOfBirth,GETDATE()) as Age,
ifkMedicalAidID
from Patients
where datepart(month,dDateOfBirth)=7

How to calculate date based on yyyy-mm-dd

I am looking for a simple query to calculate someones age based on yyyymmdd. I don't need to keep the records updated throughout time, I just need the age as of today.
Example - 19731026 is the birthdate for one record. I want to create a new column named age and calculate that birthdate to their current age which would be 48 years old.
If your database is Oracle you can use:
select floor(months_between(sysdate, to_date('19731026','YYYYMMDD'))/12) as age
from dual;
AGE
----------
48

Rounding dates in SQL

I'd like to figure out the age of a person based on two dates: their birthday and the date they were created in a database.
The age is being calculated in days instead of years, though. Here's my query:
SELECT date_of_birth as birthday, created_at, (created_at - date_of_birth) as Age
FROM public.users
WHERE date_of_birth IS NOT NULL
The date_of_birth field is a date w/o a timestamp, but the created_at field is a date with a timestamp (e.g. 2017-05-06 01:27:40).
And my output looks like this:
0 years 0 mons 9645 days 1 hours 27 mins 40.86485 secs
Any idea how can I round/calculate the ages by the nearest year?
Using PostgreSQL.
If you are using MS SQLServer than you could
CONVERT(DATE, created_at)
and than calculate difference in months like
DATEDIFF(month, created_at, GETDATE())/12
means you can use reminder in months to add or substract one year.
In PostgreSQL, dates are handled very differently to MSSQL & MySQL. In fact it follows the SQL standard very well, even if it’s not always intuitive.
To actually calculate the age of something, you can use age():
SELECT age(date1,date1)
Like all of PostgreSQL’s functions, there are variations of data type, and you may need to do something like this:
SELECT age(date1::date,date1::date)
or, more formally:
SELECT age(cast(date1 as date),cast(date1 as date))
The result will be an interval, which displays as a string :
SELECT age(current_date::date,'1981-01-17'::date);
-- 36 years 3 mons 22 days
If you just want the age in years, you can use extract:
SELECT extract('year' from age(current_date::date,'1981-01-17'::date));
Finally, if you want it correct to the nearest year, you can apply the old trick of adding half an interval:
extract('year' from age(current_date::date,'1981-01-17'::date)+interval '.5 year');
It’s not as simple as some of the other DBMS products, but it’s much more flexible, if you can get your head around it.
Here are some references:
https://www.postgresql.org/docs/current/static/functions-datetime.html
http://www.sqlines.com/postgresql/how-to/datediff

DB2 SQL - How to check if an employee reached age 70 years and 6 months in current year?

I want to fetch an employee who reaches age 70 years and 6 months in year. That is, he should reached 70 years and 6 months between 01/01 and 12/31 of current year. Please help.
My table has the employees date of birth, datatype DATE. Database system DB2.
We know the employee will reach 70 years 6 months in this year when:
The year of birth is 70 years before the current year and month of birth is no later than June
OR the year of birth is 71 years before the current year and the month of birth is no earlier than July.
Therefore we must filter as such:
SELECT Name FROM Employees
WHERE DateOfBirth BETWEEN '7/1/' + CAST((YEAR(GETDATE())-71) AS varchar) AND '7/1/' + CAST((YEAR(GETDATE())-70) AS varchar)
Try step by step.
If person becomes 70.5 years old on 2013-01-01, then his birthday is 1942-07-01.
If person becomes 70.5 years old on 2013-12-31, then his birthday is 1943-06-30.
Calculate these values in your programming language.
Then
SELECT * FROM empleyees WHERE birstday >= '1942-07-01' AND birstday <= '1943-06-30';
What RDBMS are you using. The answer needs date functions, and each RDBMS uses its own proprietary date functions.
In SQL Server, you could
Select case When birthdate Between
DateAdd(month, -6, Dateadd(year, -70, dateadd(dd, 1 +
datediff(dd, 0, getdate())-datepart(dy,getdate()), 0)))
And DateAdd(month, 6, Dateadd(year, -70, dateadd(dd,
datediff(dd, 0, getdate())-datepart(dy,getdate()), 0)))
(A.BRTH_DT BETWEEN (SUBSTR (CHAR(DATE(&CURRDATE) - 71 YEARS),1,4)||'-07-01') AND (SUBSTR (CHAR(DATE(&CURRDATE) - 70 YEARS),1,4)||'-06-30')
This SQL worked to fetch the Age 70.5 employees. &CURRDATE refers to Current Date.

calculating age from sysdate and birthdate using SQL Server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to calculate age in T-SQL with years, months, and days
I'm simply trying to calc age (in years) using a birthdate variable
1932-04-29 00:00:00.000
and SYSDATETIME( ) in SQL Server, where by
SELECT year(Sysdatetime() - Birthdate) as Age
produces (surprisingly) : 1980
What did I miss? I expected to get 80!
Calculating age is not as simple as it might first appear.
If you use Datediff you get a difference in absolute years, which is not the age.
eg
select DATEDIFF(yy, '1980-12-31', getdate())
will return 32, whereas the age of the person in question is 31.
This might be accurate enough for your purposes.
More accurate, but still wrong, you can use
select convert(int,DATEDIFF(d, '1933-10-31', getdate())/365.25)
which is right most of the time.
Or you can write a more complex function....
CREATE Function [dbo].[F_GetAge]( #RefDate Datetime,#Birthdate Datetime) Returns Int as
/*
200040916 Thomas Wassermann
*/
Begin
Declare #Alter Int
if #RefDate>#Birthdate
Select #Alter=(DatePart(yy,CAst(#Refdate-#Birthdate -1 as Float))-1900)
else select #Alter=0
Return(#Alter)
end
Quick and dirty. Can have some errors bepending on leap years, etc.
-- quick and dirty age in years
declare #birthday datetime
set #birthday = '19320429'
-- this is pretty close, but could have problems with leap years, etc.
select floor(datediff(day, #birthday, CURRENT_TIMESTAMP) / 365.25)
What happens here is the following:
both dates get converted to floats as number of days since 1900-01-01T00:00:00
the floats get subtracted from each other yielding the number of days between them
the result gets converted back to a date by adding the number of days to the base date
To correctly calculate the difference use DATEDIFF: http://msdn.microsoft.com/en-us/library/ms189794.aspx
But there is still a problem with that. See here for a complete solution: How to calculate age (in years) based on Date of Birth and getDate()