我想在我的网站上显示用户统计信息,返回年龄组的百分比,如:
-13 years : $percent %
13-15 years : $percent %
15-20 years : $percent %
23+ : $percent %
在我的mysql表中,我有一列birth_date返回datatime(yyyy-mm-dd)。
你有提示或想法吗?
答案 0 :(得分:4)
select case when year(curdate() - birth_date) < 13
then '< 13 years'
when year(curdate() - birth_date) between 13 and 14
then '13 - 14 years'
when year(curdate() - birth_date) between 15 and 20
then '15 - 20 years'
when year(curdate() - birth_date) >= 23
then '+23 years'
end as `description`,
(select count(*) from your_table) / count(*)
from your_table
group by case when year(curdate() - birth_date) < 13 then 1
when year(curdate() - birth_date) between 13 and 14 then 2
when year(curdate() - birth_date) between 15 and 20 then 3
when year(curdate() - birth_date) >= 23 then 4
end
答案 1 :(得分:3)
如果你想要纯sql:
SELECT COUNT(*)
FROM [table_name]
WHERE birth_date < DATE_ADD(NOW(),INTERVAL 13 YEAR)
WHERE birth_date >= DATE_ADD(NOW(),INTERVAL 13 YEAR)
AND birth_date < DATE_ADD(NOW(),INTERVAL 15 YEAR)
--etc
否则我建议使用php来创建日期。
您可以将所有查询合并在一起并创建和sql视图,例如:
CREATE VIEW statistics AS
SELECT "0-13" as age ,COUNT(*) as total
FROM table_name
WHERE birth_date < DATE_ADD(NOW(),INTERVAL 13 YEAR)
UNION
SELECT "13-15" as age ,COUNT(*) as total
FROM table_name
WHERE birth_date >= DATE_ADD(NOW(),INTERVAL 13 YEAR)
AND birth_date < DATE_ADD(NOW(),INTERVAL 15 YEAR)
UNION
SELECT "15-20" as age ,COUNT(*) as total
FROM table_name
WHERE birth_date >= DATE_ADD(NOW(),INTERVAL 15 YEAR)
AND birth_date < DATE_ADD(NOW(),INTERVAL 20 YEAR)
UNION
SELECT "20-23" as age ,COUNT(*) as total
FROM table_name
WHERE birth_date >= DATE_ADD(NOW(),INTERVAL 20 YEAR)
AND birth_date < DATE_ADD(NOW(),INTERVAL 23 YEAR)
UNION
SELECT "23+" as age ,COUNT(*) as total
FROM table_name
WHERE birth_date >= DATE_ADD(NOW(),INTERVAL 23 YEAR)
然后你可以查询:
SELECT * from statistics
答案 2 :(得分:3)
Pure SQL:
SELECT
`group`,
COUNT(*) as `count`
FROM
`user`
INNER JOIN (
SELECT
0 as `start`, 12 as `end`, '0-12' as `group`
UNION ALL
SELECT
13, 14, '13-14'
UNION ALL
SELECT
15, 19, '15-19'
UNION ALL
SELECT
20, 150, '20+'
) `sub`
ON TIMESTAMPDIFF(YEAR, `birth_date`, NOW()) BETWEEN `start` AND `end`
GROUP BY `group` WITH ROLLUP;
其他任何内容都可以通过PHP
计算。
答案 3 :(得分:0)
将datetime作为时间戳返回,与now.offset(years = ??)进行比较,在数组中进行分类,然后计算记录。