如何连续添加起始行和下一行的值

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

我只想创建一个 sql 查询,结果类似于图像上的结果,类似于 SQL 中的斐波那契数列。

例如

Column 1: 10 ,那么 Result 列的值为 Result: 10 ,因为那是第一行。 , 那么假设column1 2nd row的值为50,那么Result 2nd row的值为60..(Result: 60)..等等.

示例如下图。

我怎样才能连续这样做?任何帮助,将不胜感激。谢谢

你可以试试这个

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

您也可以使用 window 函数。

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

试试这个

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

在fiddlehttp://sqlfiddle.com/#!6/a8f56/2

中找到解决方案

如果您使用 MSSQL2012 或更高版本,您可以使用 OVER 子句。

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