繁体   English   中英

T-SQL如何获取行,直到运行量可以满足所提供的限制

[英]T-SQL How to get rows until the running quantity can accomodate the supplied limit

我有这样的数据:

Id  Qty   Price
----------------
1    5    200
2   20    230
3   40    180
4   10    200

我需要根据数量限制获取行。

例如,使用Qty = 30 ,我应该得到以下输出:

Id  Qty   Price
----------------
1    5    200
2   20    230
3   40    180

您可以尝试结合使用SUM和LAG函数的分析版本来解决您的问题。

测试数据

drop table if exists #test;

create table #test (
    Id int,
    Qty int,
    Price numeric(10,2)
)

insert into #test ( Id, Qty, Price )
    values ( 1 ,  5 , 200 ) , ( 2 , 20 , 230 ) , ( 3 , 40 , 180 ) , ( 4 , 10  , 200 );

with 
cte1 as ( select Id, Qty, Price, SUM(Qty) OVER(ORDER BY ID) as Total from #test ),
cte2 as ( select t1.*,COALESCE(LAG(Total) OVER (ORDER BY ID),0) as PrevTotal from cte1 t1 )
select Id, Qty, Price from cte2 where PrevTotal <= 30;

结果

在此处输入图片说明

我只会做:

select t.*
from (select t.*,
             sum(qty) over (order by id) as running_qty
      from t
     ) t
where running_qty - qty < 30;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM