gpt4 book ai didi

SQL选择动态记录数

转载 作者:行者123 更新时间:2023-12-02 23:25:53 25 4
gpt4 key购买 nike

使用 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 部分)中获取正确的“顶级”产品记录?

最佳答案

尝试这样的事情:

;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

关于SQL选择动态记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4189476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com