Share of parent
Same grand-total trick, but PARTITION BY the parent instead of the whole set.
The task
You want each product's sales and what percent of its category that represents, not of the whole catalogue.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT p.category, p.name,
SUM(oi.quantity * oi.unit_price) AS product_sales,
ROUND(100.0 * SUM(oi.quantity * oi.unit_price)
/ SUM(SUM(oi.quantity * oi.unit_price)) OVER (PARTITION BY p.category), 1) AS share_of_category
FROM order_items oi
JOIN products p ON p.id = oi.product_id
GROUP BY p.category, p.name
ORDER BY p.category, product_sales DESC;
Как это работает
The GROUP BY produces one sales row per product; the windowed SUM then totals those rows per category, which is the parent denominator. Dividing the product's own grouped SUM by it gives the share. It is the percentage-of-total recipe with PARTITION BY, and the same decimal-division warning applies.
Variations
Two levels at once: category and catalogue share
SELECT p.category, p.name,
ROUND(100.0 * SUM(oi.quantity * oi.unit_price)
/ SUM(SUM(oi.quantity * oi.unit_price)) OVER (PARTITION BY p.category), 1) AS share_of_category,
ROUND(100.0 * SUM(oi.quantity * oi.unit_price)
/ SUM(SUM(oi.quantity * oi.unit_price)) OVER (), 1) AS share_of_catalogue
FROM order_items oi
JOIN products p ON p.id = oi.product_id
GROUP BY p.category, p.name;
Questions that come up
What defines 'the parent' here?
Whatever you PARTITION BY. The partition key must also be a GROUP BY key so the window sees the aggregated rows; category, region and month are the usual parents.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.