创建类别mysql后计算百分比和总数

时间:2014-11-12 13:38:57

标签: mysql

我的查询

SELECT 
    trage,
    CASE trage 
        WHEN '<18' THEN SUM(CASE WHEN AGE <18 THEN 1 ELSE 0 END)
        WHEN '18-24' THEN SUM(CASE WHEN AGE >= 18 AND AGE <= 24 THEN 1 ELSE 0 END)
        WHEN '25-34' THEN SUM(CASE WHEN AGE >= 25 AND AGE <= 34 THEN 1 ELSE 0 END)
        WHEN '35-44' THEN SUM(CASE WHEN AGE >= 35 AND AGE <= 44 THEN 1 ELSE 0 END)
        WHEN '45-54' THEN SUM(CASE WHEN AGE >= 45 AND AGE <= 54 THEN 1 ELSE 0 END)
        WHEN '>=55' THEN SUM(CASE WHEN AGE >= 55 THEN 1 ELSE 0 END)
    END Total
FROM 
(   SELECT 
        t_personne.pers_date_naissance, 
        t_personne.pers_date_inscription, 
        TIMESTAMPDIFF(Year, t_personne.pers_date_naissance, t_personne.pers_date_inscription) 
        - CASE 
            WHEN MONTH(t_personne.pers_date_naissance) > MONTH(t_personne.pers_date_inscription) 
             OR (MONTH(t_personne.pers_date_naissance) = MONTH(t_personne.pers_date_inscription) 
             AND DAY(t_personne.pers_date_naissance) > DAY(t_personne.pers_date_inscription))
            THEN 1 ELSE 0 
          END AS AGE
    FROM t_personne
) AS Total
CROSS JOIN
(   SELECT '<18' trage UNION ALL
    SELECT '18-24' UNION ALL
    SELECT '25-34' UNION ALL
    SELECT '35-44' UNION ALL
    SELECT '45-54' UNION ALL
    SELECT '>=55'
)a
GROUP BY trage
ORDER BY FIELD(trage, '<18', '18-24', '25-34', '35-44', '45-54', '>=55')

它给出了一个表格,其中包含两列trage和所有类别的总计

如何为列Total和%

添加行百分比TOTAL

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

目前,你无法做到这一点。为了支持这个MySQL需要它仍然没有的窗口函数支持。如果您需要这些功能,我建议您切换到PostgreSQL。

另请看一下这个问题:MySql using correct syntax for the over clause