I need a database with two tabels. I need to JOIN them, group the records and then display top 5 rows from each group. Here is my initial query without top N records:
SELECT customerId, itemId, count(itemId) as num FROM Orders JOIN OrderItems ON orderId=orderId ORDER BY num DESC GROUP BY customerId
I suppose I would need a ROWNUM and PARTITION BY here, but I have no idea how to combine them with JOIN tables. Could you please help me?
2
Answers
To retrieve the top 5 rows per group in your query, you can use a subquery with the ROW_NUMBER function and a PARTITION BY clause.
If you want to display the 5 orders with the most items, you could use this:
For displaying the top 5 items in each order, it is a bit more complex, because you cannot use windowed functions in
WHERE
orORDER BY
.For this, you need a subquery to retrieve the ranking and sort/filter the result.
If that is not your intent, please give an example for your intended result.