Diff值按日期时间记录最后两个记录

时间:2012-04-25 11:47:33

标签: mysql sql

我有id, item_id, value (int), run (datetime)的表格,我需要在每个* item_id *的最后两个运行之间选择值diff 。

2 个答案:

答案 0 :(得分:3)

SELECT item_id, ABS(value1 - value2) AS diff
FROM (  SELECT h.item_id, h.value AS value1, h2.value AS value2
        FROM (  SELECT id, item_id, value
                FROM table_name
                GROUP BY item_id
                ORDER BY run DESC) AS h
        INNER JOIN (    SELECT id, item_id, value
                        FROM table_name
                        ORDER BY run DESC) AS h2
        ON h.item_id = h2.item_id AND h.id != h2.id
        GROUP BY item_id) AS h3

我相信这应该适合你。只需将table_name替换为更正名称。

<强>解释
基本上我以run DESC顺序加入表格,基于item_id和id加入它们。然后我再次GROUP BY他们删除潜在的第3等案件。最后,我通过ABS(value1 - value2)计算它们之间的差异。

答案 1 :(得分:1)

    SELECT t2.id, t2.item_id, (t2.value- t1.value) valueDiff, t2.run
    FROM ( table_name AS t1 
           INNER JOIN 
           table_name AS t2 
           ON t1.run = (SELECT MAX(run) FROM table_name where run < t2.run) 
                 and t1.item_id = t2.item_id) 

这假设你想要记录和记录之间的差异与之前的运行