6

我经常使用以下查询,但我很确定必须有更有效的方法来做到这一点。

基本上,我从用户表中计算人们出生的几十年:

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'))
4

2 回答 2

6

您可以计算十年并使用它对用户进行分组:

SELECT
    COUNT(id) AS howmany,
    CEIL((`yyyy`+1)/10) AS decade,
    yyyy
FROM `bday`
GROUP BY decade
于 2012-05-19T08:39:52.597 回答
0

计算人们出生的几十年:

select substring(yyyy, 1, 3) || '0''s' decade, count(*) howmany
from bday
group by decade
于 2012-05-19T08:43:38.043 回答