Learn SQL/Advanced/Window Functions/SQL Top N per Group

SQL Top N per Group

One of the most common real interview questions — and it requires a step window functions can't do alone.

What & Why

The top-N-per-group pattern assigns a partitioned rank and keeps only ranks up to N. It answers questions like the two highest-activity rows per group without running a separate query for every group.

See How It Works

BUSINESS QUESTION

Return the two highest-page-view sessions for every device type.

iduser_idstarted_atended_atpage_viewsdevice
50011012024-01-16 14:20:00+002024-01-16 14:52:00+008desktop
50021022024-02-10 11:10:00+002024-02-10 11:18:00+003mobile
50031032024-03-13 08:10:00+002024-03-13 09:04:00+0012desktop
50041042024-04-03 12:00:00+00NULL1tablet
50051052024-04-04 09:00:00+002024-04-04 09:21:00+007mobile
50061062024-04-05 10:15:00+002024-04-05 10:42:00+005tablet
50071072024-04-06 13:05:00+002024-04-06 13:38:00+0010desktop
Watch every session rank, then keep two per deviceStep 1 of 2
ROW_NUMBER() OVER (PARTITION BY device ORDER BY page_views DESC, id)
session_iddevicepage_viewsview_rank
5003desktop121
5007desktop102
5001desktop83
5005mobile71
5002mobile32
5006tablet51
5004tablet12

The inner query ranks all seven sessions and restarts numbering for each device.

EXAMPLE QUERY
WITH ranked AS (
  SELECT
    id AS session_id,
    device,
    page_views,
    ROW_NUMBER() OVER (
      PARTITION BY device
      ORDER BY page_views DESC, id
    ) AS view_rank
  FROM growth.sessions
)
SELECT session_id, device, page_views, view_rank
FROM ranked
WHERE view_rank <= 2
ORDER BY device, view_rank;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario