计算行之间的差异MySQL

时间:2017-07-04 14:39:22

标签: mysql mysql-python

我有一张这样的表:

+----------+-----+--------+----+---------+-----+--------+ 
| Week     | #X  | Diff_X | #Y | Diff_Y  | #Z  | Diff_Z |
+----------+-----+--------+----+---------+-----+--------+ 
| 22       | 25  | Null   | 13 | NULL    |  0  | NULL   |
| 23       | 25  | Null   | 18 | NULL    |  12 | NULL   |
| 24       | 39  | Null   | 15 | NULL    |  16 | NULL   |
+----------+-----+--------+----+---------+-----+--------+ 

每周更新一次,每周更新一次。

我如何计算每周之间每个值之间的差异?并将它们放在指定的栏目中。

所以期望的结果应如下所示:

+----------+-----+--------+----+---------+-----+--------+ 
| Week     | #X  | Diff_X | #Y | Diff_Y  | #Z  | Diff_Z |
+----------+-----+--------+----+---------+-----+--------+ 
| 22       | 25  | 0      | 13 | 0       |  2  | 0      |
| 23       | 25  | 0      | 18 | 5       |  12 | 10     |
| 24       | 39  | 14     | 15 | -3      |  16 | 4      |
+----------+-----+--------+----+---------+-----+--------+ 

我完全不知道该怎么做,所以任何形式的帮助都会非常感激!

1 个答案:

答案 0 :(得分:0)

UPDATE mytable t1
INNER JOIN mytable t2 ON t1.Week + 1 = t2.Week
SET t2.`Diff_X` = t2.`#X` - t1.`#X`,
    t2.`Diff_Y` = t2.`#Y` - t1.`#Y`,
    t2.`Diff_Z` = t2.`#Z` - t1.`#Z`