[英]Calculate Percentage in MySql
I want to calculate percentage on basis on amount for a particular product for my table.I want to add percentage column on basis of the calculation according to the following table.The table column are : 我想根据表中特定产品的数量计算百分比。我想根据下表根据计算添加百分比列。表格列为:
Item_Category : It gives the item name
Item_Amount : It gives the sum of the particular item
The query which i have used is : 我使用的查询是:
select Item_Category,
(SUM(Item_Amount)/100000) as Total,
quarter(Invoice_date) as Quarter,
year(Invoice_date) as Year
from `cmpsldata`
where Site='BDD1'
and Item_code LIKE 'FG%'
and Invoice_type='Excise'
group by Year,Item_Category,Quarter
order by Total desc
Table :
| Item_Category | Total | Quarter | Year |
| Product A | 78.65 | 1 | 2015 |
| Product B | 65.54 | 1 | 2015 |
| Product C | 45.78 | 1 | 2015 |
This is the current table now i need to add 1 more column which gives me percentage calculation of the Product A, B , C(individually). 这是当前表,现在我需要再增加1列,这样我就可以分别计算产品A,B和C的百分比。
Until MySQL supports windowing functions like SUM() OVER(...) there is a need to use subqueries to gather the extra data required for the percent calculation. 在MySQL支持诸如SUM()OVER(...)之类的窗口函数之前,需要使用子查询来收集百分比计算所需的额外数据。
Not quite sure what you need, but hopefully this will help: 不太确定您需要什么,但是希望这会有所帮助:
SELECT
i.Item_Category
, i.Total
, i.Quarter
, i.Year
, (i.Total * 100.0) / y.Total as Pct
FROM (
SELECT
Item_Category
, (SUM(Item_Amount) / 100000) AS Total
, quarter(Invoice_date) AS Quarter
, YEAR(Invoice_date) AS Year
FROM `cmpsldata`
WHERE Site = 'BDD1'
AND Item_code LIKE 'FG%'
AND Invoice_type = 'Excise'
GROUP BY Year
, Item_Category
, Quarter
) i
INNER JOIN (
SELECT
(SUM(Item_Amount) / 100000) AS Total
, quarter(Invoice_date) AS Quarter
, YEAR(Invoice_date) AS Year
FROM `cmpsldata`
WHERE Site = 'BDD1'
AND Item_code LIKE 'FG%'
AND Invoice_type = 'Excise'
GROUP BY Year
, Quarter
) y ON i.year = y.year
AND i.quarter = y.quarter
ORDER BY i.Total DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.