我有一个带有A列和B列的sql表,以及第三列C = A-B。
例如:
Row 1: A = 10, B = 8, C = 2
Row 2: A = 7, B = 8, C = -1
Row 3: A = 0, B = 8, C = -8
我想在第四列D中总结第三列C的值。列D应该是最后一行的D值加上当前行的C值。例如:
Row 1: A = 10, B = 8, C = 2, D = 2
Row 2: A = 7, B = 8, C = -1, D = 1
Row 3: A = 0, B = 8, C = -8, D = -7
我尝试使用以下SQL:
SELECT myTable2.*, D = LAG(D) + C OVER (ORDER BY Id)
FROM
(
SELECT myTable.*, C = myTable.A - myTable.B
FROM
(
SELECT Id = 1, A = 10, B = 8
UNION
SELECT Id = 2, A = 7, B = 8
UNION
SELECT Id = 3, A = 0, B = 8
) myTable
) myTable2
ORDER BY myTable2.Id ASC
我可以LAG(C)
,但不能LAG(D)
。我有什么想法可以实现这个目标吗?
感谢。
答案 0 :(得分:1)
由于您的数据没有ID,我按A降序排序。
SELECT A, B, A-B C, SUM(A-B) OVER (ORDER BY A DESC) D FROM (VALUES (10,8),(7,8),(0,8)) A(A,B)
A B C D
----------- ----------- ----------- -----------
10 8 2 2
7 8 -1 1
0 8 -8 -7
(3 row(s) affected)
答案 1 :(得分:0)
你可以试试这个:
SELECT myTable2.*, D = ISNULL(SUM(C) OVER (ORDER BY Id), 0)
FROM
(
SELECT myTable.*, C = myTable.A - myTable.B
FROM
(
SELECT Id = 1, A = 10, B = 8
UNION
SELECT Id = 2, A = 7, B = 8
UNION
SELECT Id = 3, A = 0, B = 8
) myTable
) myTable2
答案 2 :(得分:0)
create table
#test
(
a int,
b int,
c int
)
insert into #test
select 1,2,3
union all
select 3,4,5
with cte
as
(
select *,0 as 'd', row_number() over (order by a,b,c) as rn
from #test
)
select *,(select sum(c+d) from cte c1 where c1.rn<=c2.rn) 'D'
from cte c2