Using SQL Server 2005, I am trying to select a certain number of records (dynamic) from one table, based on another table to get what that number of records needs to be.
Table 1 has a Category ID and the number of records I want returned for that category.
Category ID TOP_Limit
----------------------
Cat 1 1
Cat 2 2
Cat 3 10
Table 2 has a Product ID, the Category ID, and a Quantity:
Product ID Category ID Quantity
---------------------------------
Part 1 Cat 1 10
Part 2 Cat 1 20
Part 3 Cat 2 100
Part 4 Cat 2 100
Part 5 Cat 2 50
Part 6 Cat 3 5
How can I write a query that will get me the correct “top” product records from Table 2 (Part 2, Part 3 & 4, Part 6)?
Try something like this: