AdvancedGROUP BY & Aggregation

Weighted average calculation

The query

SQL
SELECT
  cat.name AS category,
  SUM(oi.unit_price * oi.qty) / NULLIF(SUM(oi.qty), 0) AS weighted_avg_price,
  SUM(oi.qty) AS total_units,
  AVG(oi.unit_price) AS simple_avg_price
FROM order_items oi
JOIN products p ON oi.product_id = p.product_id
JOIN categories cat ON p.cat_id = cat.cat_id
GROUP BY cat.cat_id, cat.name
ORDER BY total_units DESC;
Tested against PostgreSQL 16

Note

Weighted average accounts for quantity sold. Different from simple average — reflects actual revenue distribution.

Tables referenced