用 windows 函数减去两列
Subtract two columns with windows function
如何减去两列:
我有 table:
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
看来你想从col1中减去col2的累计量:
select id, col1, col2,
(col1 - sum(col2) over (order by id)) as col3
from t;
您需要递归 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
如何减去两列:
我有 table:
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
看来你想从col1中减去col2的累计量:
select id, col1, col2,
(col1 - sum(col2) over (order by id)) as col3
from t;
您需要递归 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