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.

SqlData Fetching

Code

snippet
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 WHERE and GROUP BY — their output is not visible to a same-level WHERE.

Putting it to use

The sales table is the working surface here.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`sales` — referenced directly, no join needed.