计算每个站点的mysql百分比

时间:2015-11-05 07:04:08

标签: mysql

我有一个columns Site, Item Amount,Item Weight的表格结构。我想计算每个网站的百分比。我已经尝试过这个查询,但错误的%值。请帮忙。

Site |  Item Amount |  Item Weight 
 A   |    1000      |    50
 B   |    800       |    35
 C   |    1500      |    65 

 Select Site, sum(Item Amount) As Amount, sum(Item Weight)
 AS MT,concat(round((Item Amount/sum(Item Amount)*100),2),%)
 AS percentage from 'table1' group by site. 

2 个答案:

答案 0 :(得分:1)

您可以使用CROSS JOIN代替使用子查询来计算总和。

SELECT t1.Site, sum(t1.`Item Amount`) As Amount, sum(t1.`Item Weight`) AS MT,
    SUM(t1.`Item Amount`) / t2.itemSum * 100 AS `Item percentage`,
    SUM(t1.`Item Weight`) / t3.weightSum * 100 AS `Weight percentage`
FROM table1 t1 CROSS JOIN
(SELECT SUM(`Item Amount`) AS itemSum FROM table1) t2 CROSS JOIN
(SELECT SUM(`Item Weight`) AS weightSum FROM table1) t3
GROUP BY t1.Site

答案 1 :(得分:1)

据我所知,您需要每个站点的百分比与数据库中的总数相比:

select
  site,
  sum(`Item Amount`) as TotalItemAmount,
  sum(`Item Amount`)*100/(select sum(`Item Amount`) from table1) as ItemAmountPercent,
  sum(`Item Weight`) as TotalItemWeight,
  sum(`Item Weight`)*100/(select sum(`Item Weight`) from table1) as ItemWeightPercent
from table1
group by site

我相信这应该是为你做的。此查询对网站进行分组。对于每个站点,它总计项目金额并将其除以整个表格中项目金额的总和。与物品重量相同。