Postgres: how to limit the number of query results by aggregate type
WITH 
cte AS ( SELECT resource_id, 
                target_id,
                relation_id, 
                ROW_NUMBER() OVER ( PARTITION BY resource_id, relation_id 
                                    ORDER BY id ) rn
         FROM associations
         WHERE relation_id IN (4, 5, 8) )
SELECT resource_id, STRING_AGG(target_id::TEXT, ','::TEXT), relation_id
FROM cte
WHERE rn &lt;= 3
GROUP BY resource_id, relation_id


fiddle