对相同符号的连续值求和

时间:2013-08-13 15:50:17

标签: mysql

一个非常新手的mysql问题。我有一个类似于下面的mysql表,其中输出列是我想要生成的

TEST_TABLE

Record_ID  Day  price_change  Output
=======================================
1          1     null          null
2          1     3             3
3          1    -1             null
4          1     0            -1
5          1     1             1
6          1    -1             null
7          1     0             null
8          1     0            -1
9          1     1             1
10         2     null          null
11         2     1             null

我要做的是将记录的price_change列中的运行总计得到,并在每次值中的符号更改,日期更改或下一个值为空时输出总计。

record_id可能并不总是连续的,所以它可以分为10,15,16,19,20等。

我试图像下面这样做(我没有处理当天的变化),但它的表现并不像我预期的那样,我不能在输出后重置变量。任何人都可以指出我正确的方向,我应该如何接近这个?

set @var := 0;
SELECT 
  rid,
  pcng,
        CASE 
       when pcng > 0 and next_price_change > 0 then @var := @var + pcng /* output null */
        when pcng < 0 and next_price_change < 0 then @var := @var + pcng /* output null */
        when pcng * next_price_change < 0 or next_price_change is null then @var + pcng
        /* how to reset the @var ??? */
      END AS output_sum
FROM (
    SELECT
        Record_ID as rid,
        Price_CHANGE as pcng,
    /* Subselect next number from next Record_ID which may not be in sequence */
    (SELECT Price_change FROM test_table WHERE Record_ID > rid ORDER BY Record_ID ASC LIMIT 1) AS next_price_change
    FROM test_table
) pcalc

1 个答案:

答案 0 :(得分:3)

变量赋值在mysql中从左到右进行求值,所以有类似

的东西
mysql> set @foo=1;
Query OK, 0 rows affected (0.00 sec)

将为您提供此功能,在整个字段列表中动态更新变量:

mysql> select @foo as first, @foo:=@foo+1 as second, @foo:=@foo+10 as third;
+-------+--------+-------+
| first | second | third |
+-------+--------+-------+
|     1 |      2 |    12 |
+-------+--------+-------+
1 row in set (0.00 sec)

现在注意变量以原始1开始,然后更新为新值。然后,如果您重新运行相同的查询:

mysql> select @foo as first, @foo:=@foo+1 as second, @foo:=@foo+10 as third;
+-------+--------+-------+
| first | second | third |
+-------+--------+-------+
|    12 |     13 |    23 |
+-------+--------+-------+
1 row in set (0.00 sec)

您从上一个查询中的最后指定值开始,并再次更新。

所以基本上,只需执行所有查询计算,然后作为SELECT中的最后字段,就可以使用新值更新变量。 e.g

SET @prev = null;
SELECT this + @prev, that - @prev, whatever * @prev, @prev := new_value