Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate age from date of birth and group each member into age range in sql

I have an sql table that stores people's details i.e id, name, DoB, registration_date and address. I would like to calculate the age of each individual and then group them into these ranges: 20-30, 31-50, 51 & over.

I know i can get the age by doing: (https://stackoverflow.com/a/1572257/3045800)

SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age

I just need to figure out how to group all people into thier respective range.

Thanks for the help

like image 333
saint Avatar asked Apr 04 '14 12:04

saint


2 Answers

Use a case to produce the age group description:

select *,
  case
    when datediff(now(), date_of_birth) / 365.25 > 50 then '51 & over'
    when datediff(now(), date_of_birth) / 365.25 > 30 then '31 - 50'
    when datediff(now(), date_of_birth) / 365.25 > 19 then '20 - 30'
    else 'under 20'
  end as age_group
from person

Note the simpler way to calculate age.

like image 90
Bohemian Avatar answered Sep 30 '22 15:09

Bohemian


You can use with construction:

with Query as (
   select FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age
          ... -- Other fields
     from MyTable
   )

   select case 
            -- whatever ranges you want
            when (Age < 20) then
              1
            when (Age >= 20) and (Age <= 30) then
              2
            when (Age > 30) and (Age <= 50) then
              3
            else
              4  
          end AgeRange,
          ...  
     from Query
 group by AgeRange
like image 21
Dmitry Bychenko Avatar answered Sep 30 '22 16:09

Dmitry Bychenko