简体   繁体   中英

Calculate percentage and total after create categories mysql

I've this query

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

it give a table with two columns trage and Total for all categories

How to add a column percentage with a line TOTAL for the column Total and %

Thanks for your help

For the time being, you can't do this. To support this MySQL needs Window Function support which it still doesn't have. If you need functions like these I would recommend switching to PostgreSQL.

Also take a look at this question: MySql using correct syntax for the over clause

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM