mysql - 比较mysql

时间:2017-12-07 10:55:33

标签: mysql

我有一个包含3列的表。基本上2但我已经生成了第3个,所以我可以将它与第一列进行比较。

DATE       |TX  |PREV_WEEK
------------------------------
2017-12-05 |52  | 2017-05-28 |
2017-12-04 |95  | 2017-05-27 |
2017-12-03 |123 | 2017-05-26 |
2017-12-02 |20  | 2017-05-25 |
2017-12-01 |66  | 2017-05-24 |
2017-11-30 |2   | 2017-05-23 |
2017-05-29 |250 | 2017-05-22 |
2017-05-28 |28  | 2017-05-21 |
2017-05-27 |85  | 2017-05-20 |

我需要的是获得一个查询/表格来比较当前天数TX与前几周的TX。因此,我需要在PREV_WEEk旁边添加一个前几周'TX(PREV_TX)的列。

有没有一种简单的方法可以使用mysql执行此操作?。

1 个答案:

答案 0 :(得分:0)

select tmp.date,
       tmp.tx,
       tmp.prev_week,
       tmp.prev_tx,
   // you can compare both tx here, like finding difference as follows
      coalesce(abs(tmp.prev_tx - tmp.tx),0) as diff
From
(
select t1.date,
       t1.tx,
       t1.prev_week,
       (select tx
        from table t2
        where t2.date = t1.prev_week
       ) as prev_tx
from table t1
group by t1.date
) tmp 
;

希望它有所帮助!