views:

66

answers:

2

I always forget how to do things like this.

I have a database table with birthdates and I want to find out how many people have the same age.

I'm trying:

SELECT TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) ) AS age, COUNT( age ) 
FROM  person 
GROUP BY age

but get the error

Unknown column 'age' in 'field list'

How can I do a group by on a named column?

A: 

Nevermind, I figured it out.

Ok, I need to use COUNT(*)

SELECT TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) ) AS age, COUNT( * ) 
FROM  person 
GROUP BY age
Matt McCormick
+5  A: 

Aliases can't be used in group by clauses, nor can it be used in other columns in the select list (yes, this sucks).

SELECT TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) ) AS age, COUNT( TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) ))
FROM  person
GROUP BY TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) )
erikkallen
This is one of those things that every developer wished would work how you think it should. I don't understand why it doesn't work... I can't imagine it would cause any real problems...
Max Schmeling
Thanks for the explanation. Yes, this part of MySQL is frustrating when it doesn't work like you think it would.
Matt McCormick