Jumat, 14 Juni 2013

Calculate an age of people in MYSQL with SQL, base on the date of birth

Sometimes we need to calculate an age of someone base on his birthday. yesterday i just found this problem when i'm creating a SIRODA app. in this app I have a table, it's name is "atlits" table, thare are some field like name, place of birth, date of birth and age. in other way I have to show the atlits data that can show us name and age. so I try to calculate the age base on date of birth and this date.
so I found the query like this :
1. my table structure :
table name : atlits,
the table have fields : name, pob, dob, address (pob mean place of birth and dob mean date of birth)

2. so I want to show name and age. the query is :
   SELECT name, YEAR(CURRENT_TIMESTAMP ) - YEAR( dob ) - CASE WHEN( (MONTH(dob)*100 + DAY(dob)) > (MONTH(CURRENT_TIMESTAMP)*100 + DAY(CURRENT_TIMESTAMP)) ) THEN 1 ELSE 0 END AS age
FROM atlits

3. taraaa, you can see the returns !

4. let me explain about the formula of age calculation above. so the first, current year minus year of date of birth and in second the year of returned will be minus 1 if (month of date of birth multiple 100 plus the day of date of birth) is greater than  (current month multiple 100 plus current date) if not, the year of the returned calculation will be ignored.

thankyou for your visiting my blog !

Tidak ada komentar:

Posting Komentar