Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way to run date/yyyy query?

Tags:

sql

mysql

I use the following query quite a lot but am pretty sure there must be a more efficient way to do it.

Basically, I am counting the decades people were born in, from within a user table:

select count(*) as howmany, yyyy from bday where (((yyyy > '1949')
AND (yyyy < '1961')) AND (user_id = '63')) UNION
select count(*) as howmany, yyyy from bday where (((yyyy > '1959')
AND (yyyy < '1971')) AND (user_id = '63')) UNION
select count(*) as howmany, yyyy from bday where (((yyyy > '1969')
AND (yyyy < '1981')) AND (user_id = '63')) UNION
select count(*) as howmany, yyyy from bday where (((yyyy > '1979')
AND (yyyy < '1991')) AND (user_id = '63')) UNION
select count(*) as howmany, yyyy from bday where (((yyyy > '1989')
AND (yyyy < '2001')) AND (user_id = '63'))
like image 490
StudioTime Avatar asked May 19 '12 08:05

StudioTime


1 Answers

You can calculate the decade and use it to group the users:

SELECT
    COUNT(id) AS howmany,
    CEIL((`yyyy`+1)/10) AS decade,
    yyyy
FROM `bday`
GROUP BY decade
like image 87
Teneff Avatar answered Oct 16 '22 19:10

Teneff