Skip to content
Advertisement

Calculate percentage using SQL

I am trying to find how I can calculate Percentage from table below

enter image description here

From the above table, I am hoping to get the data with percentage like below. However my SQL statement below returns all percentage value to 0. Please advise what I missed. Thanks

Select SupplierID
    , ProductID
    , Month
    , Year
    , Count(SupplierID) AS TotalSales
    , (count(SupplierID)* 100/(Select Count (*) From ProductOrder)) AS Percentage     
From ProductOrder
Order by Year DESC, Month DESC

enter image description here

Advertisement

Answer

That’s integer division. Both operands to the division are integers, so the result is given as integer as well; 3/4 is 0, not 0.75. To work around this, just turn one of the arguments to a decimal.

I would also recommend using window functions rather than a subquery:

select supplierid, month, year, 
    count(*) as totalsales, 
    100.0 * count(*) / sum(count(*)) over(partition by month, year) as percentage
from productorder
group by supplierid, month, year
order by year desc, month desc, supplierid

Notes:

  • your original code is not a valid aggregation query to start with: it is missing a group by clause

  • your sample data indicates that you want the ratio per supplier against the total of the month and year, while your query (attempts to) compute the overal ratio; I fixed that too

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement