I'm having trouble generating a query that I'm sure is possible. I have a products table and a product_changes table. I would like to select the average of the product_changes.rank field for the top 30 lowest values for each associated product.
Here are the relevant table definitions:
CREATE TABLE products (
  id integer NOT NULL,
  created_at timestamp without time zone
);
CREATE TABLE product_changes (
  id integer NOT NULL,
  product_id integer,
  rank integer,
  created_at timestamp without time zone
);
Here's what I'm trying:
SELECT products.id, avg_rank 
FROM "products" 
JOIN (
  SELECT product_id, AVG(rank) avg_rank
  FROM product_changes 
  GROUP BY product_id, rank
  ORDER BY rank ASC NULLS LAST
  LIMIT 10) pc ON pc.product_id = products.id
WHERE avg_rank IS NOT NULL
LIMIT 10
However, this is giving me the same average of the lowest 30 rank values for each row of the results. That would seem like the ON clause of the JOIN isn't working, but I'm sure it's just my misunderstanding of something.
 
     
     
    