用windows函数减去两列

时间:2015-12-05 10:23:34

标签: sql sql-server tsql sql-server-2014

我如何减去两列:

我有桌子:

      ID      COL 1      COL 2
     -------------------------
       1      200.00     70.00
       2      200.00     30.00
       3      200.00     90.00
       4      200.00    110.00

Col1 - COL2但要继续为每一行和值减少先前的值

我的输出如下:

      ID      COL 1      COL 2     [COL3 AS RESULT]
     -------------------------
       1      200.00     70.00          130 
       2      200.00     30.00          100
       3      200.00     90.00           10
       4      200.00    110.00         -100

2 个答案:

答案 0 :(得分:2)

看起来你想从col1中减去col2的累积量:

select id, col1, col2,
       (col1 - sum(col2) over (order by id)) as col3
from t;

答案 1 :(得分:0)

您需要递归CTE才能获得总计 -

with cte as
(
select id,col1,col2,cast(col1 - col2 as decimal(5,2)) as val
from #a
where id = 1
union all
select b.id,b.col1,b.col2,cast(a.val - b.col2 as decimal(5,2))
from cte as a
inner join #a as b
on b.id = a.id + 1
)select * from cte