计算Mysql中先前和当前记录之间的差异

时间:2012-03-13 07:18:01

标签: mysql

如何计算当前和之前记录之间的差异。

这是表格示例

| rid    | time                |    data |
|10000038| 2012-03-13 12:30:18 |     100 |
|10000052| 2012-03-13 12:30:18 |     120 |
|10000053| 2012-03-13 12:30:18 |     140 |
|10000038| 2012-03-13 12:20:18 |     160 |
|10000052| 2012-03-13 12:20:18 |     180 |
|10000053| 2012-03-13 12:20:18 |     160 |
|10000038| 2012-03-13 12:10:18 |     100 |
|10000052| 2012-03-13 12:10:18 |     160 |
|10000053| 2012-03-13 12:10:18 |     160 |

这里我希望得到结果,

| rid    | time                |    data | DIf |
|10000038| 2012-03-13 12:30:18 |     100 | 0   |
|10000052| 2012-03-13 12:30:18 |     120 | 20  |
|10000053| 2012-03-13 12:30:18 |     140 | 20  |
|10000038| 2012-03-13 12:20:18 |     160 | 20  |
|10000052| 2012-03-13 12:20:18 |     180 | 20  |
|10000053| 2012-03-13 12:20:18 |     160 |-20  |
|10000038| 2012-03-13 12:10:18 |     100 |-60  |
|10000052| 2012-03-13 12:10:18 |     160 | 60  |
|10000053| 2012-03-13 12:10:18 |     160 | 0   |

注意:查看表,每次在表中转储三个具有单独资源ID的数据。如何找到差异?

3 个答案:

答案 0 :(得分:1)

您可以使用LAG()函数,该函数让您知道上一条记录中的值。

就您而言,

lag(data, 1) over (order by time) as previou_val

将显示以前的数据!

答案 1 :(得分:0)

确保表格中有一个diff列。然后,每当您使用新值更新表时,请执行此操作

UPDATE 
   `tablename` 
SET 
    data = 120,
    diff = 120 -
    (
        SELECT prev_data
        FROM (
          SELECT data AS prev_data
          FROM tablename
          WHERE `id` = '1'
        )
       AS prev_data
    )
WHERE 
   id='1';

经测试& WORKS

Demo

答案 2 :(得分:-1)

你可以使用PHP, 当你循环结果集时, 将值保存在临时变量中。 假设你得到的数据是一个整数,用它来比较下一行。

$previousRow = 0; //initiates value for preceeding row

while($row = mysql_fetch_assoc($result)){
   $currentRow = $row['data']; //gets current row
  //gets difference between the two variables
  $difference = $currentRow - $previousRow; 
  echo "\$difference = $difference<br>\n";
  $previousRow = $currentRow; //reassigns previous row
  //display otherfield
  //display $diff
 }