2013-02-21 95 views
0

我的表看上去如下因素:差异tabels和unixtimestamp

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

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

+0

在我目前的工作流程可能的解决方案可能是: – FireFox 2013-02-21 12:13:19

回答

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