MySQL-在特殊条件下从当天数据中减去前一天数据

时间:2019-03-17 12:09:01

标签: mysql

我有以下示例数据:

  ID | DATE  | LOCATION | DATA 
 ----|-------|----------|------ 
   1 | MAR-1 |        1 |  100 
   2 | MAR-2 |        1 |  120 
   3 | MAR-3 |        1 |  160 
   4 | MAR-3 |        2 |   80 
   5 | MAR-4 |        1 |  170 
   6 | MAR-4 |        2 |  100 
   7 | MAR-5 |        1 |   10 
   8 | MAR-6 |        1 |   50 

我需要从当天减去前一天的数据,然后将结果放入“增量”列中,该结果在每个位置也都是唯一的。在此示例中,数据来自功率计,功率计会定期重置为零。因此,我需要测试“增量”结果是否为负,如果是,则仅复制“增量”列中的原始“数据”值。根据上面的示例数据,我想要以下输出:

  ID | DATE  | LOCATION | DATA | DELTA |            COMMENT            
 ----|-------|----------|------|-------|------------------------------- 
   1 | MAR-1 |        1 |  100 | NULL  | NO PREVIOUS DATA EXISTS       
   2 | MAR-2 |        1 |  120 | 20    |                               
   3 | MAR-3 |        1 |  160 | 40    |                               
   4 | MAR-3 |        2 |   80 | NULL  | NO PREVIOUS DATA EXISTS       
   5 | MAR-4 |        1 |  170 | 10    |                               
   6 | MAR-4 |        2 |  100 | 20    |                               
   7 | MAR-5 |        1 |   10 | 10    | DELTA WOULD BE - SO TAKE DATA 
   8 | MAR-6 |        1 |   50 | 40    |             

我正在使用MySQL v5.7。

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来查找如下输出。

SELECT id,date,location,data, 
       CASE 
         WHEN nv < 0 THEN data 
         ELSE nv 
       END AS Delta 
FROM   (SELECT *, 
               data - (SELECT  data 
                       FROM   mytable t1 
                       WHERE  t1.id < t2.id 
                              AND t1.location = t2.location 
                       ORDER  BY id DESC
                       limit 1)nv 
        FROM   mytable t2) t 

Online Demo

输出

| id  | date  | location | data | Delta |
| --- | ----- | -------- | ---- | ----- |
| 1   | MAR-1 | 1        | 100  |       |
| 2   | MAR-2 | 1        | 120  | 20    |
| 3   | MAR-3 | 1        | 160  | 40    |
| 4   | MAR-3 | 2        | 80   |       |
| 5   | MAR-4 | 1        | 170  | 10    |
| 6   | MAR-4 | 2        | 100  | 20    |
| 7   | MAR-5 | 1        | 10   | 10    |
| 8   | MAR-6 | 1        | 50   | 40    |