MSSQL中没有游标,循环等的困难SQL查询

sas*_*fut 0 sql sql-server select

这是表:

Product_ID  Operation_Type   Operation_Sum    
1             ‘in’           100.00    
2             ‘in’           200.00    
3             ‘out’          50.00    
4             ‘in’           100.00
Run Code Online (Sandbox Code Playgroud)

我必须计算收入.

结果表必须如下所示:

Product_ID  Operation_Type  Operation_Sum      Summary
1           ‘in’            100.00             100.00
2           ‘in’            200.00             300.00
3           ‘out’           50.00              250.00
4           ‘in’            100.00             350.00
Run Code Online (Sandbox Code Playgroud)

如果我没有列'Operation_Type',如果我不得不计算增长收入,我会写下一个查询:

select Product_ID, Operation_Type, Operation_Sum,    
(    
select sum(Operation_Sum) from Table1 as t1 
where t1.Id <= Table1.Id    
)    
from Table1
Run Code Online (Sandbox Code Playgroud)

但我有'Operation_Type'.我不能使用游标,周期,临时表等.它必须只有一个查询.

该怎么办?

Len*_*art 5

由于您的dbms支持窗口功能,并且定义良好(product_id):

select product_id, op_type, op_sum
     , sum(case when op_type = 'in' then 1 else -1 end * op_sum) 
           over (order by product_id) as summary 
from t;
Run Code Online (Sandbox Code Playgroud)