0

我的表如下所示:

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,则该值应为零。

一个提示/提示将不胜感激。谢谢

4

1 回答 1

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
于 2013-02-22T01:20:53.313 回答