簡體   English   中英

使用PHP和MYSQL的年齡組統計信息

[英]Age Groups stats with PHP and MYSQL

我想在我的網站上顯示用戶統計信息,返回年齡組的百分比,如:

-13 years : $percent %
13-15 years : $percent %
15-20 years : $percent %
23+ : $percent %

在我的mysql表中,我有一個返回datatime的列birth_date(yyyy-mm-dd)。

你有提示或想法嗎?

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

如果你想要純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

純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計算出來。

將datetime作為時間戳返回,與now.offset(years = ??)進行比較,在數組中進行分類,然后計算記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM