Aller au contenu

How do I select the first row of each group in SQL?

par Équipe NextData

0

I have a table with several rows per customer and I need exactly one row per customer: the most recent order, with all of its columns. A plain GROUP BY only gives me the aggregated columns, not the rest of the row.

Signaler

1 réponse

0

Number the rows inside each group with a window function, then keep the first one. This works on PostgreSQL, SQL Server, Oracle, MySQL 8+, BigQuery and Snowflake.

WITH ranked AS (
    SELECT o.*,
           ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at DESC, id DESC) AS rn
    FROM orders AS o
)
SELECT *
FROM ranked
WHERE rn = 1;

PARTITION BY defines the group, ORDER BY defines which row comes first.

PostgreSQL has a shorter form:

SELECT DISTINCT ON (customer_id) *
FROM orders
ORDER BY customer_id, ordered_at DESC, id DESC;

Things to get right:

  • Ties. If two rows share the same ordered_at, the winner is arbitrary unless you add a tie-breaker such as id.
  • Keeping ties on purpose. Use RANK() instead of ROW_NUMBER() to return every row tied for first place.
  • Index. An index on (customer_id, ordered_at DESC) matches the grouping and ordering of this query; check the execution plan to see whether it is used.

Avoid the old pattern of selecting non-aggregated columns next to a GROUP BY: where the database accepts it, the values returned for those columns are not guaranteed to come from the same row.

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