Using Window Functions To Get Top N per Group

Description

Given the schema presented below write a query, which uses a window function, that returns two most viewed posts for every category.

Order the result set by:

  1. category name alphabetically

  2. number of post views largest to lowest

  3. post id lowest to largest

Note:

  • Some categories may have less than two or no posts at all.

  • Two or more posts within the category can be tied by (have the same) the number of views. Use post id as a tie breaker - a post with a lower id gets a higher rank.

Schema

categories

 Column     | Type                        | Modifiers
------------+-----------------------------+----------
id          | integer                     | not null
category    | character varying(255)      | not null

posts

Desired Output

The desired output should look like this:

  • category_id - category id

  • category - category name

  • title - post title

  • views - the number of post views

  • post_id - post id

Solutions

πŸ—ƒοΈ Sql

Last updated

Was this helpful?