Skip to content

Instantly share code, notes, and snippets.

@cjjavellana
Created July 1, 2015 15:11
Show Gist options
  • Save cjjavellana/5d39ecf24a39c83e503e to your computer and use it in GitHub Desktop.
Save cjjavellana/5d39ecf24a39c83e503e to your computer and use it in GitHub Desktop.
Top 3 items of each group
select cat.name, sub.name, x.name, x.price, x.qty from product_categories cat
left join product_categories sub on cat.id = sub.product_category_id
left OUTER JOIN (
SELECT a.*
FROM products a
LEFT JOIN products b ON a.product_category_id = b.product_category_id AND a.id <= b.id
GROUP BY a.name
HAVING count(*) <= 3
ORDER BY a.product_category_id
) x on x.product_category_id = sub.id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment