Hi SUJAYS,
Refer below sample query, Accordingly to your table data change below query.
SQL
DECLARE @Test AS TABLE([Date] DATETIME,TotalRestOfDay INT)
INSERT INTO @Test VALUES('12-1-2016',10)
INSERT INTO @Test VALUES('12-2-2016',12)
INSERT INTO @Test VALUES('12-3-2016',10)
INSERT INTO @Test VALUES('12-4-2016',11)
INSERT INTO @Test VALUES('12-5-2016',12)
INSERT INTO @Test VALUES('12-6-2016',10)
INSERT INTO @Test VALUES('12-7-2016',11)
INSERT INTO @Test VALUES('12-8-2016',10)
INSERT INTO @Test VALUES('12-9-2016',9)
INSERT INTO @Test VALUES('12-10-2016',10)
INSERT INTO @Test VALUES('12-11-2016',13)
DECLARE @Test1 AS TABLE([Date] DATETIME,TotalRestOfDay INT,Diff INT)
DECLARE @Counter INT,@Diff1 INT
SET @Counter = 1
SET @Diff1 = 0
WHILE (@Counter <= (SELECT COUNT(*) FROM @Test))
BEGIN
DECLARE @Date DATETime,@TotalRestOfDay INT,@Diff INT
SELECT @Date = Date,@TotalRestOfDay = TotalRestOfDay,@Diff = TotalRestOfDay
FROM (SELECT ROW_NUMBER() OVER( ORDER BY (SELECT 0)) Row_Num,Date,TotalRestOfDay FROM @Test) t
WHERE t.Row_Num = @Counter
IF(@Counter > 1)
BEGIN
INSERT INTO @Test1 (Date,TotalRestOfDay,Diff)
VALUES (@Date,@TotalRestOfDay,@Diff1 - @Diff)
END
ELSE
BEGIN
INSERT INTO @Test1 (Date,TotalRestOfDay,Diff)
VALUES (@Date,@TotalRestOfDay,0)
END
SET @Diff1 = @Diff
SET @Counter = @Counter + 1
CONTINUE;
END
SELECT * FROM @Test1
Output
Date |
TotalRestOfDay |
Diff |
2016-12-01 |
10 |
0 |
2016-12-02 |
12 |
-2 |
2016-12-03 |
10 |
2 |
2016-12-04 |
11 |
-1 |
2016-12-05 |
12 |
-1 |
2016-12-06 |
10 |
2 |
2016-12-07 |
11 |
-1 |
2016-12-08 |
10 |
1 |
2016-12-09 |
9 |
1 |
2016-12-10 |
10 |
-1 |
2016-12-11 |
13 |
-3 |