Reputation: 131
I want to calculated the weighted average price in SQL for each level i.e. L0,L1, and L2. Currently, I only know the formula for calculating the general weighted avg = sum(price*units)/sum(units).
SELECT COALESCE((price*units)/units, 0) AS price_weighted
How should I roll it up to any category I want?
Upvotes: 2
Views: 898
Reputation: 1269643
Is this what you want?
select l1,
sum(units * price) / nullif(sum(units), 0) as weighted_price
from t
group by l1;
Upvotes: 1