基于Id和unix时间戳的不同表

时间:2013-02-21 10:53:09

标签: mysql unix-timestamp

我的表格如下:

unix_timestap   ID  value
1351058019      1   500
1351058029      1   505
1351058039      9   105
1351058049      9   200
1351076620      1   520

我希望能够生成一个新列,其中包含当前值与第一个可用“过去”值之间每个ID的值之间的差异。过去我的意思是unixtimestamp没有在原始表中按顺序放置。

输出结果为:

unix_timestap   ID  value    difference
1351058019      1   500      0
1351058029      1   505      5
1351058039      9   105      0
1351058049      9   200      95
1351076620      1   520      15

如果不存在先前的unix_timestamp,则该值应为零。

提示/提示将非常感激。 感谢

1 个答案:

答案 0 :(得分:0)

如果仍然需要解决方案

select
  t3.unix_timestamp, t3.id, t3.value, ifnull(t3.value - t5.value, 0) as diff
from test1 t3
  join (
        SELECT t1.unix_timestamp, t1.id, max(t2.unix_timestamp) as old_stamp
        FROM `test1` t1
          left join test1 t2 on t1.id = t2.id and t1.unix_timestamp > t2.unix_timestamp
        group by t1.unix_timestamp, t1.id) as t4
  on t3.unix_timestamp = t4.unix_timestamp and t3.id = t4.id
left join test1 t5 on t4.old_stamp = t5.unix_timestamp and t4.id = t5.id