MySQL查询计算总列的百分比

时间:2014-03-31 18:26:19

标签: mysql sql

如何转换此结果:

Group     |  Sum
Services  | 11120.99
Vendas    | 3738.00

分为:

Group     |  Sum
Services  | 74.84
Vendas    | 25.16

也就是说,第二个显示结果为总数的百分比。

这就是我的尝试:

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

3 个答案:

答案 0 :(得分:4)

你可以离开加入未分组或拆分的总和,并将其除以总和查询。通过这种方式,您只需执行一次总选择以获得更快的运行时间

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

你可以通过以下几种方式做到这一点。一种是在select子句中使用子查询。如下所示,这假设category_id中的table1列始终与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;

我也改变了group by条款。 group byselect使用相同的列是个好主意。我在所有列引用中添加了表别名,这是另一种好的做法。