如何更新SQL Server中的运行记录

时间:2014-05-06 09:06:44

标签: sql sql-server

在下面的表中,我想更新第二行开头,第一行关闭,依此类推。 结算列计算为(开盘+总计)

  ID    opening  Total      Closing
  ---   --------  ------------  -------------
   1    0   3015591.25  3015591.25
   2    0   2146798.4   NULL
   3    0   3015591.25  NULL
   4    0   2146798.4   NULL
   5    0   3015591.25  NULL
   6    0   2146798.4   NULL
   7    0   3015591.25  NULL
   8    0   2146798.4   NULL

输出应为:

       ID    opening      Total     Closing
       ---   --------   ------------  -------------
        1   0           3015591.25  3015591.25
        2   3015591.25  2146798.4   5162389.65
        3   5162389.65  3015591.25  8177981.25
        4   8177980.9   2146798.4   10324779.4
        5   10324779.3  3015591.25  13340370.25
        6   13340370.55 2146798.4   15487168.4
        7   15487168.95 3015591.25  18502759.25
        8   18502760.2  2146798.4   20649557.4

任何解决方案。

3 个答案:

答案 0 :(得分:3)

您可以使用此查询,该查询基于以下事实:您的收盘价值是所有先前行(包括当前行)的总和之和,而开盘价相同,不包括当前行。

update table1
set
    Opening = isnull((select sum(total) from table1 t where t.ID < table1.ID), 0),
    Closing = (select sum(total) from table1 t where t.ID <= table1.ID)

这是SQL Fiddle,表明它有效。

由于此解决方案重新计算所有行,从头开始获取总数,因此更适合较少数量的记录。

答案 1 :(得分:2)

涉及WHILE循环的答案。

--Simulated your table
DECLARE @tbl TABLE 
(
    ID INT,
    opening FLOAT, 
    Total FLOAT,
    Closing FLOAT
)

--Testing values
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(1,0,3015591.25,3015591.25)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(2,0,2146798.4,NULL)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(3,0,3015591.25,NULL)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(4,0,2146798.4,NULL)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(5,0,3015591.25,NULL)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(6,0,2146798.4,NULL)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(7,0,3015591.25,NULL)
INSERT INTO @tbl(ID, opening , Total ,Closing) VALUES(8,0,2146798.4,NULL)

--Solution starts from here
DECLARE @StartCount INT, @TotalCount INT, @OPENING FLOAT,@CLOSING FLOAT

SELECT @TotalCount = MAX(ID) FROM @tbl;
SET @StartCount = 2;

WHILE(@StartCount <= @TotalCount)
BEGIN
    SELECT @OPENING = ISNULL(Closing, 0) FROM @tbl WHERE ID = @StartCount - 1
    SELECT @CLOSING = (@OPENING + Total) FROM @tbl WHERE ID = @StartCount

    UPDATE @tbl
    SET opening = @OPENING,
    Closing = @CLOSING
    WHERE ID = @StartCount

    SELECT @StartCount = @StartCount + 1
END

SELECT * FROM @tbl

希望这有帮助

答案 2 :(得分:0)

试试这个:

select id, sum(total) over(order by id)-total as opening, total, sum(total) over(order by id) as closing
from #t