Share Of Partition Total Per Row
Compute each row's share of its partition and of the grand total by dividing by SUM() OVER with PARTITION BY and an empty window.
Code
WITH sales(region, rep, revenue) AS (
VALUES
('emea', 'ada', 1200),
('emea', 'kim', 800),
('apac', 'raj', 500),
('apac', 'mei', 300),
('amer', 'zoe', 1000)
)
SELECT
region,
rep,
revenue,
-- 分区内 share:PARTITION BY 让 SUM 只在该 region 里累计
ROUND(100.0 * revenue / SUM(revenue) OVER (PARTITION BY region), 1) AS region_share,
-- 空 OVER 的窗口覆盖整个结果集,得到全局 share
ROUND(100.0 * revenue / SUM(revenue) OVER (), 1) AS total_share
FROM sales
ORDER BY region, revenue DESC;Inside the snippet
At its core this is a single SELECT statement against sales.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Watch out for
- Window functions are evaluated after
WHEREandGROUP BY— their output is not visible to a same-levelWHERE.
Putting it to use
The sales table is the working surface here.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which relations are involved here?
- `sales` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.