2016-11-17 48 views
0

我有一个像减法在MySQL

Id_indicator Value trend Date_data 
1 0 0 2011-08-18 09:16:15 
1 2 1 2011-08-18 10:16:15 
1 1 -1 2011-08-18 11:16:15 
1 2 1 2011-08-18 12:16:15 
2 21 0 2011-08-18 13:16:15 
2 21 0 2011-08-18 14:16:15 
2 21 0 2011-08-18 15:16:15 
3 3 0 2011-08-18 16:16:15 
3 4 1 2011-08-18 17:16:15 
3 4 0 2011-08-18 18:16:15 
4 4 0 2011-08-18 19:16:15 

我需要找出什么是基于id_indicator先前值之间的差异,在右侧输入该值增加一列的表。例如,作为

Id_indicator Value trend Date_data Difference 
1 0 0 2011-08-18 09:16:15 0 
1 2 1 2011-08-18 10:16:15 2 
1 1 -1 2011-08-18 11:16:15 -1 
1 2 1 2011-08-18 12:16:15 1 
2 21 0 2011-08-18 13:16:15 0 
2 21 0 2011-08-18 14:16:15 0 
2 21 0 2011-08-18 15:16:15 0 
3 3 0 2011-08-18 16:16:15 0 
3 4 1 2011-08-18 17:16:15 1 
3 4 0 2011-08-18 18:16:15 0 
4 4 0 2011-08-18 19:16:15 0 

感谢

+2

的可能的复制[MySQL的 - 从先前行减去值,由基团](http://stackoverflow.com/questions/13196190/mysql-subtracting-value - 从在先排基团的通过) – CGritton

回答

0

你可以先创建一个查询,让你以前的时间戳每个ID和日期,然后加入到这个查询。

像这样(未测试):

SELECT * -- t1.value - t2.vaue... 
FROM 
    (SELECT t1.Id_indicator, 
      t1.Date_data, 
      max(t2.Date_date) AS prev_date_data 
    FROM TABLE t1 
    LEFT JOIN TABLE t2 ON t1.Id_indicator = t2.Id_indicator 
    AND t2.Date_data < t1.Date_data 
    GROUP BY 1, 2) AS lookup 
LEFT JOIN TABLE t1 ON t1.Id_indicator = lookup.Id_indicator 
AND t1.Date_data = lookup.Date_data 
LEFT JOIN TABLE t2 ON t2.Id_indicator = lookup.Id_indicator 
AND t2.Date_data = lookup.prev_date_data