首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL select动态记录数

SQL select动态记录数
EN

Stack Overflow用户
提问于 2010-11-16 06:27:06
回答 2查看 1.9K关注 0票数 5

使用SQL Server2005,我试图根据另一个表从一个表中选择一定数量的记录(动态),以获得需要的记录数量。

表1有一个category ID和我希望为该类别返回的记录数。

代码语言:javascript
复制
Category ID  TOP_Limit
----------------------  
Cat 1        1
Cat 2        2
Cat 3        10

表2包含产品ID、类别ID和数量:

代码语言:javascript
复制
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部分)中获得正确的“顶级”产品记录?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-16 07:00:18

尝试如下所示:

代码语言:javascript
复制
;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
票数 5
EN

Stack Overflow用户

发布于 2010-11-16 06:52:59

我想这样就行了。

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4189476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档