如何创建一个表,其中字段的值基于mysql中的上一行

Date    |  Column_A  | Column_B
Day 1   |    5       |    7
Day 2   |    -3      |   7 + (-3) = 4
Day 3   |    8       |   4 + 8 = 12
Day 4   |    -21     |   12 + (-21) -> 0 (see formula on row n)
Day n-1 |    ...     |    Column_B(n-1)
Day n   |Column_A(n) |    IF(Column_B(n-1) + Column_A(n) >= 0, Column_B(n-1) +
                                                                Column_A(n), 0)

如何在Mysql中填充Column_B?

最佳答案 您可以将ID作为ID添加到表中吗?

如果是的话……您可以使用以下代码:

    DECLARE   @count INT;
    DECLARE   @i INT;
    DECLARE  @temp INT;
    SET @count =( select count(*) from myTBL)
    SET @i=2
    WHILE (@i <=@count)
         BEGIN
             SET @temp=(select Column_A from myTBL where ID=@i)+ (select Column_B from myTBL where ID=@i-1);
             IF (@temp>0)      update myTBL set Column_B=@temp where ID=@i
             ELSE update myTBL set Column_B=0  where ID=@i
         SET @i = @i+1
         END
点赞