计算sql中所有对象的连续几天的值差异

时间:2011-03-03 06:26:00

标签: mysql

我有一个包含对象,索引,日期和值的表:

+--------------+-------+------------+------------+
| object       | index | date       | value      |
+--------------+-------+------------+------------+
| 32           | 1     | 2011-02-25 | 2100000000 | 
| 32           | 2     | 2011-02-25 | 27800000   | 
| 32           | 3     | 2011-02-25 | 5700000    | 
| 32           | 1     | 2011-02-26 | 2100000000 | 
| 32           | 2     | 2011-02-26 | 28700000   | 
| 32           | 3     | 2011-02-26 | 5800000    | 
| 32           | 1     | 2011-02-27 | 2200000000 | 
| 32           | 2     | 2011-02-27 | 29500000   | 
| 32           | 3     | 2011-02-27 | 5900000    | 
+--------------+-------+------------+------------+

我需要一个查询,其中每个对象索引的连续两天之间的值不同 所以像这样

+--------------+-------+------------+------------+
| object       | index | date       | value_24h  |
+--------------+-------+------------+------------+
| 32           | 1     | 2011-02-26 | 0          | 
| 32           | 2     | 2011-02-26 | 0          | 
| 32           | 3     | 2011-02-26 | 100000     | 
| 32           | 1     | 2011-02-27 | 100000000  | 
| 32           | 2     | 2011-02-27 | 800000     | 
| 32           | 3     | 2011-02-27 | 100000     | 
+--------------+-------+------------+------------+

这在mysql中是否可行,或者我在程序(python)中更好地计算这些值。 或者不同/更好的表格布局会有帮助吗?

谢谢,
迈克尔

2 个答案:

答案 0 :(得分:0)

SELECT t2.object,t2.index,t2.date,t2.value-t1.value
FROM table t1, table t2
    WHERE t1.object=t2.object AND t1.index=t2.index
        AND t2.date=DATE_ADD(t1.date, INTERVAL 1 DAY);

答案 1 :(得分:0)

您可以尝试使用变量:

SELECT object, `index`, `date`, value, diff
FROM (
    SELECT object, `index`, `date`, value,
        IF (@idx = `index`, value - @prev, 0) AS diff,
        @idx := `index`,
        @prev := value
    FROM tableName, (SELECT @idx := NULL, @prev := NULL) dm
    ORDER BY `index`, `date`
) rs
ORDER BY `date`, `index`

注意:如果您要查询单个对象(如OP中所示),这将起作用,如果不是这种情况,则需要添加另一级变量来跟踪对象:

SELECT object, `index`, `date`, value, diff
FROM (
    SELECT object, `index`, `date`, value,
        IF (@obj = object AND @idx = `index`, value - @prev, 0) AS diff,
        @obj := object,
        @idx := `index`,
        @prev := value
    FROM tableName, (SELECT @obj := NULL, @idx := NULL, @prev := NULL) dm
    ORDER BY object, `index`, `date`
) rs
ORDER BY object, `date`, `index`