MySQL查询获取累积值

时间:2012-02-10 13:43:26

标签: mysql

此问题与previous question有关。我想在表格中的行中获得差异每日值,如下所示:

    Date           | VALUE
--------------------------------
"2011-01-14 11:00" |   2
"2011-01-14 19:30" |   5
"2011-01-15 13:30" |   7
"2011-01-15 23:50" |   6
"2011-01-16 9:30"  |   10
"2011-01-16 18:30" |   15

查询获取最新每日值与之前最新每日值之间的差异/累积。

SELECT
  t1.dt AS date,
  t1.value - t2.value AS value
FROM
  (SELECT DATE(date) dt, MAX(date), VALUE as value FROM table GROUP BY dt) t1
JOIN
  (SELECT DATE(date) dt, MAX(date), VALUE as value FROM table GROUP BY dt) t2
    ON t1.dt = t2.dt + INTERVAL 1 DAY

结果如下:

Date               | VALUE
---------------------------
"2011-01-15 00:00" |  -1
"2011-01-16 00:00" |   6

但是我也需要第一天的累积值。一般来说,如果前一天不存在,我需要一天的累积值。像这样:

  Date             | VALUE
---------------------------
"2011-01-14 00:00" |   3
"2011-01-15 00:00" |  -1
"2011-01-16 00:00" |   6

1 个答案:

答案 0 :(得分:0)

在使用您选择的语言迭代结果集时,您几乎肯定会更好地处理这些差异,但以下查询应该可以正常工作

SELECT
    `t1`.`date`,
    `t1`.`value`,
    IFNULL((
        SELECT CAST(`t1`.`value` AS SIGNED) - CAST(`t2`.`value` AS SIGNED)
        FROM `table` `t2`
        WHERE `t2`.`date` < `t1`.`date`
        ORDER BY `date` DESC
        LIMIT 1
    ), `t1`.`value`)
FROM `table` `t1`
ORDER BY `date` ASC;