[SOLVED] Divide the sum of each group by the grand total

Issue

I want to get the sum of group A and B separately, and divide each by the total sum.

I tried to use this:

select name, sum(qt)
from ntbl
group by name 
order_id name qt
1 A 12
2 A 20
3 B 33
4 B 45

Result should be as:

name qt dv
A 32 0.29
B 78 0.70

Solution

You can combine aggregate and window functions together:

select name
     , sum(qt) as sum_qt
     , sum(qt) / sum(sum(qt)) over () * 100 as pct_qt
from t
group by name

Answered By – Salman A

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *