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

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:

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