<% query = "select case when rank <= 10 then result.name else '#{t(:other)}' end, sum(result.amount) from(select sumProduct.name, sumProduct.amount, rank() over (order by sumProduct.amount desc) as rank from (SELECT products.name, sum(order_items.amount) as amount FROM order_items JOIN products ON order_items.product_id = products.id INNER JOIN orders ON orders.id =order_items.order_id And Extract(month from orders.date) = Extract(month from (now() - interval '1 month')) And Extract(year from orders.date) = Extract(year from now()) group by products.name order by amount desc) sumProduct order by rank) result GROUP BY case when rank <= 10 then result.name else '#{t(:other)}' end" @data = ActiveRecord::Base.connection.execute(query) %>