How to continously add values of starting row and next row to it

雨燕双飞 提交于 2019-12-13 00:37:58

问题


i just want to create an sql query and the result is something like on the image., something like Fibonacci sequence in SQL.

Ex.

Column 1: 10 , then the value of Result column is Result: 10 , since that is the first row. , then assuming that the value of column1 2nd row is 50, then the value of Result 2nd row will be 60.. (Result: 60).. and so on.

Sample is the image below.

How can i do that continuously ? any help would be appreciated. Thanks


回答1:


If you are using MSSQL2012 or higher you can use OVER clause.

SELECT t2.id, t2.value, SUM(t2.value) OVER (ORDER BY t2.id) as [Result]
FROM   Test01 t2
ORDER BY t2.id;

sql fiddle demo




回答2:


You can try this

CREATE TABLE #TEST(ID INT,VALUE INT)
INSERT INTO #TEST VALUES
(1,10),(2,20),(3,30),(4,40),(5,50),(6,60),(7,70)

;WITH CTE
as
(
   SELECT ID,VALUE,VALUE AS RESULT FROM #TEST WHERE ID=1
   UNION ALL
   SELECT T.ID,T.VALUE,T.VALUE+C.RESULT
   FROM #TEST T INNER JOIN CTE C ON T.ID = C.ID+1
)

SELECT * FROM CTE




回答3:


Try this

select Id, value,
(select sum(t2.value) from TEST01 t2 where t2.id <= t1.id ) 
as Result
from TEST01 t1

Find the solution in fiddle http://sqlfiddle.com/#!6/a8f56/2




回答4:


You could also use a window function.

DECLARE @myTable TABLE(ID INT, val INT);

INSERT INTO @myTable VALUES (1,10),
                            (2,7),
                            (3,-4),
                            (4,1);
SELECT ID, 
       val,
       SUM(val) OVER (ORDER BY ID 
                      ROWS BETWEEN UNBOUNDED PRECEDING 
                      AND CURRENT ROW) AS result
FROM @myTable
ORDER BY ID;

ID  val  result
--  ---  ------
1   10   10
2   7    17
3   -4   13
4   1    14


来源:https://stackoverflow.com/questions/32240354/how-to-continously-add-values-of-starting-row-and-next-row-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!