COUNT OVER Partition Annotates Rows

COUNT, MAX, and AVG OVER (PARTITION BY) stamp every row with its group's aggregates, so detail rows survive alongside group totals.

SqlData Fetching

Code

snippet
-- COUNT OVER (PARTITION BY) annotates rows with group aggregates
-- GROUP BY 会塌缩行;窗口聚合给每行标注所在组的汇总
CREATE TEMP TABLE orders (
    id          int PRIMARY KEY,
    customer    text NOT NULL,
    total_cents int NOT NULL
);

INSERT INTO orders VALUES
    (1, 'acme', 2500),
    (2, 'acme', 1900),
    (3, 'acme', 6100),
    (4, 'lin',  990),
    (5, 'lin',  1200);

SELECT
    id,
    customer,
    total_cents,
    -- 每行都带上本组的订单数与最大单:行数不塌缩
    count(*) OVER (PARTITION BY customer)                   AS orders_of_customer,
    max(total_cents) OVER (PARTITION BY customer)           AS biggest_order,
    round(avg(total_cents) OVER (PARTITION BY customer), 1) AS avg_order
FROM orders
ORDER BY customer, id;

Group totals without collapsing rows

GROUP BY would shrink five order rows to two customers; count(*) OVER (PARTITION BY customer), max(total_cents) OVER (PARTITION BY customer), and round(avg(total_cents) OVER (PARTITION BY customer), 1) instead stamp each detail row with its group’s aggregates and keep every row in the output. The partition is the customer column, so acme’s three orders all carry the same three annotations, as do lin’s two.

The annotated result

 id | customer | total_cents | orders_of_customer | biggest_order | avg_order
----+----------+-------------+--------------------+---------------+-----------
  1 | acme     |        2500 |                  3 |          6100 |    3500.0
  2 | acme     |        1900 |                  3 |          6100 |    3500.0
  3 | acme     |        6100 |                  3 |          6100 |    3500.0
  4 | lin      |         990 |                  2 |          1200 |    1095.0
  5 | lin      |        1200 |                  2 |          1200 |    1095.0

acme’s average is (2500 + 1900 + 6100) / 3 = 3500.0 and lin’s is (990 + 1200) / 2 = 1095.0 — every row of a partition repeats its group’s numbers, which is what “detail rows survive alongside group totals” means here.

The line that carries the annotation

count(*) OVER (PARTITION BY customer)                   AS orders_of_customer,

Swapping the window aggregate for a plain GROUP BY aggregate would force the detail columns out of the SELECT — the OVER clause is what lets both live in one result set.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`orders` — referenced directly, no join needed.