用前一行余额减去当前行剩余余额

时间:2015-04-16 04:38:24

标签: sql sql-server

如何在查询中完成此类操作。如果我在存储过程中作为参数传递的总量为673000,那么我需要这样做:

    Declare @TotalAmount money

    @TotalAmount = 673000

    Col1   Col2  Col3
   Test1  45    672955  --(I want to subtract 673000  from Col2 data)  673000-45
   Test2  30    672925  --(I want to subtract 30 from the remaining amount of col3)
   Test3  100   672825  --(I want to subtract 100 from the remaining amount of col3)

任何帮助将不胜感激。我正在使用sql server 2012

4 个答案:

答案 0 :(得分:1)

DECLARE @amount decimal
DECLARE db_cursor CURSOR FOR  

SELECT amount 
FROM TABLE


OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @amount 

WHILE @@FETCH_STATUS = 0  
BEGIN  

     @TotalAmount = @TotalAmount - @amount 
     FETCH NEXT FROM db_cursor INTO @amount 
END  

CLOSE db_cursor  
DEALLOCATE db_cursor 

答案 1 :(得分:0)

假设您希望ORDER基于Col1,在SQL Server 2012及更高版本中,您可以执行以下操作

DECLARE @TotalAmount money

SET @TotalAmount = 673000

;WITH CTE as 
(
  SELECT 'Test1' col1 ,45 col2
   UNION ALL SELECT 'Test2'  ,30
   UNION ALL SELECT 'Test3'  ,100
)
SELECT col1,col2,@TotalAmount - SUM(col2)OVER(ORDER BY col1 ) col3
FROM CTE
ORDER BY col1;

对于SQL Server 2012之前的任何版本,您可以使用像这样的相关查询

DECLARE @TotalAmount MONEY

SET @TotalAmount = 673000

;WITH CTE as 
(
  SELECT 'Test1' col1 ,45 col2
   UNION ALL SELECT 'Test2'  ,30
   UNION ALL SELECT 'Test3'  ,100
)
SELECT col1,col2,(SELECT @TotalAmount - SUM(col2) FROM CTE c2 WHERE c2.col1 <= c1.col1 ) col3
FROM CTE c1
ORDER BY col1;

答案 2 :(得分:0)

Declare @TotalAmount money
SELECT @TotalAmount = 673000


Declare @table table
(
    Amount money,
    RunningTotal money
)

insert @table (Amount) values(45), (30), (100)

UPDATE @table SET @TotalAmount = RunningTotal = @TotalAmount - Amount 

SELECT * FROM @table

结果

Amount  RunningTotal
45.00   672955.00
30.00   672925.00
100.00  672825.00

答案 3 :(得分:0)

试试这个

Declare @TotalAmount money,@col1 varchar(10),@col2 money,@prevcol3 money,@Firstrow int =1 

set    @TotalAmount = 673000



create table #temp
(
        Col1  varchar(10) ,
        Col2  money,
        Col3  money
)


declare cur cursor
for select col1,col2 
    from   tab
    order  by col1 asc

open cur

fetch next from cur into @col1,@col2

while @@FETCH_STATUS = 0
begin 

    if @Firstrow = 1
    begin
        insert into #temp
        select @col1,@col2,@TotalAmount-@col2
        set @prevcol3 = @TotalAmount-@col2

        set @Firstrow =  0
    end
    else
    begin 
        insert into #temp
        select @col1,@col2,@prevcol3-@col2
        set @prevcol3 = @prevcol3-@col2
    end

    fetch next from cur into @col1,@col2
end

close cur
deallocate cur

select * From #temp
drop table #temp