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

时间:2012-10-24 13:58:04

标签: 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?

3 个答案:

答案 0 :(得分:1)

您可以将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

答案 1 :(得分:1)

我创建了一个可以带来的选择,我找不到将它放入更新的方法。

set @col_c:=7;
select *,if(dt!=1,
@col_c:=@col_c+if(col_a<0,col_a,col_a),0) as with_neg_values,
if(@col_c<0,0,@col_c) as col_tot 
from t1

SQLFIDDLE:http://www.sqlfiddle.com/#!2/105aa/3

答案 2 :(得分:0)

更新查询:

 update table1 firstInstance, tabe1 secondInstance
 set firstInstance.column_B = 
         (IF(sIFNULL(secondInstance.column_B,0) + 12 >= 0, 
                                        IFNULL(secondInstance.column_B,0) + 12, 0) 
             +firstInstance.column_A)
 where  DATEDIFF(secondInstance.date, firstInstance.date) = 1;

SELECT Query:

 SELECT firstInstance.DATE, firstInstance.COLUMN_A,
       (IF(IFNULL(secondInstance.column_B,0) + 12 >= 0, 
                                         IFNULL(secondInstance.column_B,0)+ 12, 0) 
             +firstInstance.column_A) AS COLUMN_B
 FROM table1 firstInstance 
 LEFT JOIN tabe1 secondInstance
 ON  DATEDIFF(secondInstance.date, firstInstance.date) = 1;