I have a User model and an Item model. I want to rank users according to the value of the items they have. I want to do the equivalent of this query:
SELECT rank() OVER (ORDER BY grand_total DESC), u.*, grand_total
FROM users AS u
JOIN
(SELECT user_id, SUM(amount) AS grand_total FROM items WHERE EXTRACT(YEAR FROM sold_at)='2012' GROUP BY user_id) AS i
ON u.id = i.user_id;
Specifically, I don't know how to join on my select.