ID=1的多加了一行数据,验证通过,你第3行的应该计算错了,不是-0.6
with TB1 AS(SELECT 1 AS ID,0.5 AS VALUE,'2020-01-01' AS TIME
UNION ALL
SELECT 1,0.7,'2020-02-01'
UNION ALL
SELECT 1,0.8,'2020-03-01'
UNION ALL
SELECT 1,1,'2020-04-01'
UNION ALL
SELECT 2,1,'2020-01-01'
UNION ALL
SELECT 2,0.4,'2020-02-01'
UNION ALL
SELECT 2,2,'2020-03-01'
UNION ALL
SELECT 3,0.6,'2020-01-01'
UNION ALL
SELECT 3,0.8,'2020-02-01'
UNION ALL
SELECT 3,0.3,'2020-03-01'
),
TB2 AS(
SELECT *,ROW_NUMBER() OVER(partition by ID order by TIME) AS iRow FROM TB1
)
SELECT S.ID,S.VALUE,S.TIME,SUM(VALUE2) FROM
(
SELECT A.*,CASE WHEN (A.iRow-B.iRow)%2=0 THEN B.VALUE ELSE -B.VALUE END AS VALUE2 FROM TB2 A
LEFT JOIN TB2 B ON A.ID =B.ID AND B.iRow<=A.iRow
)S
GROUP BY S.ID,S.VALUE,S.TIME
ORDER BY ID,TIME