Preetesh Gaitonde
Preetesh Gaitonde

Reputation: 459

What is an easy way of percentage calculation in SQL?

I have a table named "Categories". I am trying to get percentage of each category as as final table.

Category         TOTAL   
Category_x       5   
Category_y       10  
Category_z       20  
Category_a       30  
Category_b       40 

Expected Table

Category         TOTAL    Overall_Percentage
Category_x       5        4.76
Category_y       10       9.523
Category_z       20       19.047
Category_a       30       28.57
Category_b       40       38.09

My Code:

SELECT Category, TOTAL, 100*(TOTAL/SUM(TOTAL)) AS Overall_Percentage
FROM Categories
GROUP BY 1,2

Upvotes: 2

Views: 2544

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269743

Use window functions:

SELECT Category, TOTAL,
       (TOTAL * 100.0 / SUM(TOTAL) OVER ()) AS Overall_Percentage
FROM Categories

Upvotes: 5

Related Questions