Aller au contenu

What is the difference between PARTITION BY and GROUP BY?

par Équipe NextData

0

Both GROUP BY and PARTITION BY split rows into groups before a calculation such as SUM or COUNT. I do not understand when to use one or the other, or why they return a different number of rows.

Signaler

1 réponse

0

The difference is what happens to the rows.

  • GROUP BY collapses each group into a single row. You get one row per group, and only grouped or aggregated columns.
  • PARTITION BY keeps every row and adds the result of the calculation next to it. It is part of a window function (OVER (...)).
-- one row per city
SELECT city, SUM(amount) AS city_total
FROM sales
GROUP BY city;

-- every sale, with its city total alongside
SELECT id, city, amount,
       SUM(amount) OVER (PARTITION BY city) AS city_total
FROM sales;

That makes window functions the right tool when you need detail and aggregate together:

SELECT id, city, amount,
       amount * 100.0 / SUM(amount) OVER (PARTITION BY city) AS pct_of_city,
       SUM(amount) OVER (PARTITION BY city ORDER BY sold_at)  AS running_total,
       RANK() OVER (PARTITION BY city ORDER BY amount DESC)   AS rank_in_city
FROM sales;

Rules of thumb:

  • A summary table (totals per category): GROUP BY.
  • Share of total, running total, rank, difference with the previous row: PARTITION BY.

Two details that often surprise:

  • Adding ORDER BY inside OVER turns a total into a running total.
  • You cannot filter on a window function in WHERE. Compute it in a subquery or CTE and filter outside.

Réponse rédigée par l'équipe NextData et relue par un expert.

Équipe NextData

Signaler

Votre réponse

Connectez-vous pour répondre