2015-11-05 68 views
1

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

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. 
+0

等等......你想要多个列的百分比吗? –

+0

显示一些数据或表结构和所需的输出。 –

+1

你的名字中有空格吗?用**'**在你的queryAnyway中保护它们,你应该使用'%'而不是% 并且不需要使用'table1',table1就可以。 –

回答

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

据我了解,你需要每个站点的百分比相比,在数据库中总:

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 

这应该为你做的,我相信。该查询对网站进行分组。对于每个站点,它总计项目数量并将其除以整个表格中的项目总数。物品重量也一样。

+0

谢谢。您的查询帮助。 – Fresher