2010-11-15 75 views
5

這是一個非常奇怪的問題來描述,所以請裸露在我身邊。SQL select動態記錄數

使用SQL Server 2005,我試圖從一個表中選擇一定數量的記錄(動態),基於另一個表來獲取該記錄數量。

表1有一個類別ID和我想要爲該類別返回的記錄數。

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

表2的產品ID,類別ID和產品數量:

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 

我如何編寫一個查詢,將讓我正確的「頂級」產品從表2的記錄(第2部分,第3部分& 4,第6部分)?

回答

5

嘗試這樣:

;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 
+0

嘿,這真是棒極了,謝謝!我試圖找出如何使用row_number,但我從來沒有看到過(分區...)之前。 – wham12 2010-11-16 14:22:25

2

我認爲這樣做。

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