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).
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.