I'm trying to group by date of birth and count based on the results, using CakePHP. Here's my query.
$data = $this->User->find('all', array(
'fields' => array(
"DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(User.dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(User.dob, '00-%m-%d')) AS age",
'COUNT(id)'
),
'group' => 'age'
));
So far, so good. The field User.dob
is date of birth, it's a DATETIME
field.
Thing is, it returns something like this:
Array
(
[0] => Array
(
[0] => Array
(
[age] => 9
[COUNT(id)] => 1
)
)
[1] => Array
(
[0] => Array
(
[age] => 10
[COUNT(id)] => 1
)
)
[2] => Array
(
[0] => Array
(
[age] => 11
[COUNT(id)] => 1
)
)
[3] => Array
(
[0] => Array
(
[age] => 12
[COUNT(id)] => 8
)
)
[4] => Array
(
[0] => Array
(
[age] => 13
[COUNT(id)] => 1
)
)
Surely there must be a better way.
And I can't even filter it. This code throws error. Unknown column 'age'
$data = $this->User->find('all', array(
'conditions' => array('age >' => 20),
'fields' => array(
"DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(User.dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(User.dob, '00-%m-%d')) AS age",
'COUNT(id)'
),
'group' => 'age'
));
By the way, these are the queries.
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(User.dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(User.dob, '00-%m-%d')) AS age, COUNT(id) FROM `users` AS `User` WHERE 1 = 1 GROUP BY age
(The age calculation routine was found in matt's blog.)