简体   繁体   中英

MySQL query to calculate percentage of total column

How to convert this result:

Group     |  Sum
Services  | 11120.99
Vendas    | 3738.00

Into:

Group     |  Sum
Services  | 74.84
Vendas    | 25.16

That is, the second displays the results as percentages of total.

This is what I tried:

SELECT categories.cat AS 'Group', SUM(atual) AS 'Sum'
FROM `table1` INNER JOIN
     categories
     ON table1.category_id=categories.id
GROUP BY categoria

you can left join a total sum that is not grouped or split up, and divide that by your sum query. this way you are just doing the total select once for faster runtime

SELECT cat, sum_atual, sum_atual/total_atual as percent_atual 
FROM
(   SELECT categories.cat AS cat, SUM(atual) AS sum_atual
    FROM `table1` 
    JOIN categories ON table1.category_id=categories.id
    GROUP BY categoria
) t
LEFT JOIN 
(   SELECT SUM(atual) as total_atual
    FROM `table1`
) t1
SELECT categories.cat AS categoria, 
       SUM(atual) * 100 / (select sum(atual) from table1) AS percentages 
FROM `table1` 
INNER JOIN categories ON table1.category_id=categories.id 
GROUP BY categoria

You can do this several ways. One is to just use a subquery in the select clause. As written below, this assumes that the category_id column in table1 always matches categories :

SELECT c.categoria AS "Group", SUM(t1.atual) AS "Sum",
       SUM(t1.atual) / (SELECT SUM(t1.atual) FROM table1) as "Percent"
FROM `table1` t1 INNER JOIN
     categories c
     ON t1.category_id = c.id
GROUP BY c.categoria;

I changed the group by clause as well. It is a good idea for the group by and select to use the same columns. And I added table aliases to all the column references, another good practice.

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