Google Search

Wednesday, June 01, 2011

calculating age groups in mysql

And so i was given the task to retrieve registered users data and break it down according to age group. i'm not very strong in mysql, so instead of calculating it in PHP, i challenged myself to complete it in one SELECT statement; and so this servers as a note-to-self for my future reference :)

the date-of-birth is of DATE data type, and the age groups required are:

18 and below | 19 - 25 | 26 and above

and here's the sql:


SELECT
sum(
if
(
( YEAR(current_date()) - YEAR(dob) ) <= 18, 1,0
)
) as "18 and below",
sum(
if
(
(( YEAR(current_date()) - YEAR(dob) ) >= 19 && ( YEAR(current_date()) - YEAR(dob) ) <= 25), 1,0
)
) as "19 to 25",
sum(
if
(
( YEAR(current_date()) - YEAR(dob) ) > 25, 1,0
)
) as "26 and above"
FROM `USER_TABLE`;


not sure if this is right, but it works for me!

0 comments:

Followers

Labels

About Me

Shah Alam, Selangor, Malaysia

Recent Posts

  © Free Blogger Templates 'Photoblog II' by Ourblogtemplates.com 2008

Back to TOP