Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate age based on multiple fields

I have a table with a date of birth column, a date of death column and the date the dataset was extracted.

I want to calculate each person’s age as either the date of their death or their age at the date of extract – not by the current date – with a new ‘Age’ column. I can’t quite work it out at the moment.

Example data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Current table

person_id birth_datetimetime death_datetime extract_date
1234 1980-04-01T00:00:00 null 2021-12-31
8765 1925-05-04T00:00:00 2018-05-T00:00:00 2021-12-31
9102 1974-05-17T00:00:00 2021-01-31T00:00:00 2021-12-31
5678 2019-09-01T00:00:00 null 2021-12-31
3456 1947-04-01T00:00:00 2016-06-14T00:00:00 2021-12-31

Desired output

person_id birth_datetimetime death_datetime extract_date Age
1234 1980-04-01T00:00:00 null 2021-12-31 41
8765 1925-05-04T00:00:00 2018-05-T00:00:00 2021-12-31 93
9102 1974-05-17T00:00:00 2021-01-31T00:00:00 2021-12-31 47
5678 2019-09-01T00:00:00 null 2021-12-31 2
3456 1947-04-01T00:00:00 2016-06-14T00:00:00 2021-12-31 69

>Solution :

Consider below approach

select *, 
  date_diff(ifnull(death_datetime, extract_date), date(birth_datetimetime), year) as age
from your_table              

if applied to sample data in your question – output is

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading