当变量具有剩余值时从列中减去变量

Subtract variable from column while variable has remaining value

我有一列具有不同的数值。我有一个名为 X 的数值变量,其值为 50000。

  rownumber           col1 
 --------------------------
     1                5000
     2                1000
     3               10000
     4               12000
     5                 300
     6               35000

 DECLARE @X AS decimal(18,2) = 50000

我需要以某种方式覆盖从 col1 到零的值,同时变量 x 具有值。如何得到下面的结果?

  rownumber            col1      col2         

     1                 5000       0     
     2                 1000       0      
     3                10000       0      
     5                  300       0      
     6                35000     13300   

如果@X = 1000 那么结果应该是:

 rownumber            col1        col2         

     1                 5000       4000        
     2                 1000       1000       
     3                10000      10000     
     4                12000      12000     
     5                  300        300      
     6                35000      35000     

你可以用 运行 和来做到这一点:

with cte as(select *, sum(col1) over(order by rn) as s from t)
select rn, col1, 0 as col2 from cte where s <= 1000 
union all
select * from (select top 1 rn, col1, s - 1000 as col2 from cte where s > 1000 order by rn)t
union all
select * from (select rn, col1, col1 as col2 from cte where s > 1000 order by rn offset 1 row)t

这是未经核实就在脑海中诞生的版本。我现在无法检查,但我认为它应该可以工作并且它是基于设置的。

想法是做一个运行总和:

rownumber  col1   s        
1          5000   5000    
2          1000   6000   
3          10000  16000    
4          12000  28000
5          300    28300      
6          35000  63300  

现在您正在选择 s <= 50000 所在的所有行。这会给你 rn{1,2,3,4,5}。请注意,您将 col2 全设为零。在第二个联合中,您选择 s > 50000 的第一行。这会给你 rn{6}。注意 col2 is 63300 - 50000 = 13300。现在,如果您有其他行,那么您将选择第三个联合中的行,但我们已经在第二个联合中选择的第一行除外。