2010-11-15 18 views
5

यह वर्णन करने के लिए वास्तव में एक अजीब समस्या है, इसलिए कृपया मेरे साथ बेकार रहें।एसक्यूएल रिकॉर्ड्स की गतिशील संख्या का चयन करें

SQL सर्वर 2005 का उपयोग करके, मैं एक तालिका से रिकॉर्ड्स (गतिशील) की एक निश्चित संख्या का चयन करने की कोशिश कर रहा हूं, यह जानने के लिए कि रिकॉर्ड्स की संख्या कितनी है।

तालिका 1 में एक श्रेणी आईडी है और रिकॉर्ड की संख्या मैं उस श्रेणी के लिए लौटा चाहता हूं।

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 से रिकॉर्ड मिल जाएगा (:

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

तालिका 2 एक उत्पाद ID, श्रेणी आईडी, और एक मात्रा है भाग 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

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 
संबंधित मुद्दे