Deviopath › PostgreSQL

Share of Category Revenue

Hard · Window Functions

An aggregate used as a window function, like SUM(x) OVER (PARTITION BY category), gives every row the total of its group without collapsing the rows.

A product's revenue is the sum of quantity * price over its order items. For every product (including products that never sold, with revenue 0.00), return category, product (the product name), revenue (rounded to 2 decimals) and pct_of_category: the product's revenue as a percent of its category's total revenue, ROUND(..., 1). If a whole category has zero revenue, pct_of_category is NULL (do not divide by zero).

Sort by category, then pct_of_category descending, then product.

Next: Second Highest Salary per Department