name, RANK() OVER (PARTITION BY react_user_id ORDER BY cnt DESC) AS rnk, cnt FROM (SELECT react_user_id, react.name, COUNT(*) AS cnt FROM messages CROSS JOIN UNNEST(reactions) AS t(react) CROSS JOIN UNNEST(react.users) AS t(react_user_id) GROUP BY react_user_id, react.name ) ) agg INNER JOIN users us ON agg.react_user_id = us.id WHERE rnk <= 5 ORDER BY react_user_id, rnk