Friday, January 23, 2009

MYSQL CASE WHEN EXAMPLE

Here's a short example of using CASE WHEN control flow statement for grouping users who write reviews by age group:

select CASE
WHEN ( FLOOR(datediff(CURRENT_DATE,DOB)/365) > 15 AND FLOOR(datediff(CURRENT_DATE,DOB)/365) < 25) THEN '15-25'
WHEN ( FLOOR(datediff(CURRENT_DATE,DOB)/365) > 25 AND FLOOR(datediff(CURRENT_DATE,DOB)/365) < 35) THEN '25-35'
WHEN ( FLOOR(datediff(CURRENT_DATE,DOB)/365) > 35 AND FLOOR(datediff(CURRENT_DATE,DOB)/365) < 50) THEN '35-50'
ELSE 'Above 50'
END as Age_Group,
count(*) as Reviews
FROM
Table names
WHERE
Field Constraints
group by Age_Group;

NOTE:
DOB:Date of Birth field



Creative Commons License

No comments:

Post a Comment