WITH RankedPurchases AS ( SELECT user_id, level, amount, ROW_NUMBER() OVER (PARTITION BY level ORDER BY SUM(amount) DESC) AS rn FROM purchases GROUP BY user_id, level ) SELECT user_id, level, amount FROM RankedPurchases WHERE rn <= 10;