[英]T-SQL How to get rows until the running quantity can accomodate the supplied limit
I have a data like this: 我有这样的数据:
Id Qty Price
----------------
1 5 200
2 20 230
3 40 180
4 10 200
I need to get the rows based on a quantity limit. 我需要根据数量限制获取行。
For example, using Qty = 30
, I should get this output: 例如,使用
Qty = 30
,我应该得到以下输出:
Id Qty Price
----------------
1 5 200
2 20 230
3 40 180
You can try a combination of the analytical version of SUM and LAG function to solve your problem. 您可以尝试结合使用SUM和LAG函数的分析版本来解决您的问题。
Test data 测试数据
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 );
Solution 解
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;
Result 结果
I would simply do: 我只会做:
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.