SQL select le nombre dynamic d'loggings

C'est un problème vraiment bizarre à décrire, alors s'il vous plaît nu avec moi.

À l'aide de SQL Server 2005, j'essaie de sélectionner un certain nombre d'loggings (dynamics) à partir d'une table, en fonction d'une autre table pour get ce que ce nombre d'loggings doit être.

Le tableau 1 a un ID de catégorie et le nombre d'loggings que je veux renvoyer pour cette catégorie.

Category ID TOP_Limit ---------------------- Cat 1 1 Cat 2 2 Cat 3 10 

Le tableau 2 a un ID de produit, l'ID de catégorie et une quantité:

 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 

Comment puis-je écrire une requête qui me permettra d'get les bons loggings de produits «top» du tableau 2 (partie 2, parties 3 et 4, partie 6)?

Essayez quelque chose comme ceci:

 ;with cte as ( select ProductID, CategoryID, Quantity, [row] = row_number() over(partition by CategoryID order by Quantity desc) from Table2 ) select t2.Product, t2.CategoryID, t2.Quantity from cte t2 join Table1 t1 on t2.CategoryID=t1.CategoryID where t2.row <= t1.TOP_Limit 

Je pense que ça va le faire.

 declare @Table1 table ( Cat int, TOP_Limit int ) declare @Table2 table ( Part int, Cat int, Quantity int ) insert into @Table1 (Cat, TOP_Limit) select 1,1 union all select 2,2 union all select 3,10 insert into @Table2 (Part, Cat, Quantity) select 2,1,20 union all select 3,2,100 union all select 4,2,100 union all select 5,2,50 union all select 6,3,5 ;with cteRowNums as ( select t2.Part, t2.Cat, t2.Quantity, ROW_NUMBER() over(partition by t2.Cat order by t2.Quantity desc, t2.Part) as rownum from @Table2 t2 inner join @Table1 t1 on t2.Cat = t1.Cat ) select c.Part, c.Cat, c.Quantity from cteRowNums c inner join @Table1 t1 on c.Cat = t1.Cat and c.rownum <= t1.TOP_Limit