如何计算总和?

时间:2017-10-31 17:09:29

标签: mysql sql

我有一个查询,它返回一个表和名称的总和:

sum                  name
2                    business1
3                    business2
4                    business3
1                    business4

我想要如下:

sum              name        precentage
2                business1     0,2
3                business2     0,3
4                business3     0,4
1                business4     0,1

我在下面尝试了查询:

SELECT  
  SUM(table1.value) AS sum,
  COUNT(SUM(table1.value)/SUM(sum) as percentage,
  table2.name
  .....
  ....
  ... 
  GROUP BY table2.name 

1 个答案:

答案 0 :(得分:1)

在MySQL中,我建议在FROM子句中使用子查询:

select . . .,
       sum(table1.value) / tsum.sum_value
from . . . cross join
     (select SUM(table1.value) as sum_value from table1) tsum