计算每个年龄段的记录

时间:2014-10-16 05:45:09

标签: mysql select subquery

我有一个mysql表

TABLE名称测试

Id INT PRIMARY KEY
Lahir Date
Gender CHAR(1)
Nama Varchar(100)
id_desa CHAR(4)

我怎样才能得到这样的报告?

id_desa 0-10 11-20 21-30 31-40 41-50
10B      1      2     0    1     8
10C      2      4     7    1     0.

3 个答案:

答案 0 :(得分:0)

尝试

select
     id_desa,
     sum(case when FLOOR(DATEDIFF(Lahir,NOW())/365) between 0 and 10 then 1 else 0 end) as '0-10',
     sum(case when FLOOR(DATEDIFF(Lahir,NOW())/365) between 11 and 20 then 1 else 0 end) as '11-20',
     sum(case when FLOOR(DATEDIFF(Lahir,NOW())/365) between 21 and 30 then 1 else 0 end) as '21-30',
     sum(case when FLOOR(DATEDIFF(Lahir,NOW())/365) between 31 and 40 then 1 else 0 end) as '31-40',
     sum(case when FLOOR(DATEDIFF(Lahir,NOW())/365) between 41 and 50 then 1 else 0 end) as '41-50'
    from tbl

答案 1 :(得分:0)

您可以尝试使用此查询。 我假设表名是name_test。

SELECT id_desa,
    (SELECT Count(*) FROM name_test WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(Now(),Lahir)), "%y")+0 BETWEEN 0 AND 10) as "0-10",     
    (SELECT Count(*) FROM name_test WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(Now(),Lahir)), "%y")+0 BETWEEN 11 AND 20) as "11-20",     
    (SELECT Count(*) FROM name_test WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(Now(),Lahir)), "%y")+0 BETWEEN 21 AND 30) as "21-30", 
    (SELECT Count(*) FROM name_test WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(Now(),Lahir)), "%y")+0 BETWEEN 31 AND 40) as "31-40", 
    (SELECT Count(*) FROM name_test WHERE DATE_FORMAT(FROM_DAYS(DATEDIFF(Now(),Lahir)), "%y")+0 BETWEEN 41 AND 50) as "41-50"
FROM name_test

答案 2 :(得分:0)

MySQL有一个非常好的函数叫做TIMESTAMPDIFF

SELECT
    id_desa,
    SUM(TIMESTAMPDIFF(YEAR, Lahir, CURRENT_DATE) BETWEEN 0 AND 10) `0-10`,
    SUM(TIMESTAMPDIFF(YEAR, Lahir, CURRENT_DATE) BETWEEN 11 AND 20) `11-20`,
    SUM(TIMESTAMPDIFF(YEAR, Lahir, CURRENT_DATE) BETWEEN 21 AND 30) `21-30`,
    SUM(TIMESTAMPDIFF(YEAR, Lahir, CURRENT_DATE) BETWEEN 31 AND 40) `31-40`,
    SUM(TIMESTAMPDIFF(YEAR, Lahir, CURRENT_DATE) BETWEEN 41 AND 50) `41-50`,
    SUM(TIMESTAMPDIFF(YEAR, Lahir, CURRENT_DATE) > 50) `50+`
FROM tablename
GROUP BY id_desa