I have the next query, what returns me categories with an array of games that assignment to them. How can I limit number of games in that array?
SELECT categories.*, COALESCE(jsonb_agg(g.*) FILTER (WHERE g.name IS NOT NULL), '[]') AS games FROM categories
LEFT JOIN games_categories gc ON categories.id = gc.category_id
LEFT JOIN games g ON gc.game_id = g.id
GROUP BY categories.id;
2
Answers
This can be done using the window function
ROW_NUMBER()
to assign a unique number to each row in a group, and then selecting only the top N rows from each group :For this data set :
Results :
Demo here
I would suggest like this – row numbering and using the
ON
condition, number of games limited to 5 in the example:You may also add an
order by
in the window definition in order to control which games to be picked into the array.