0

我有一个运行总数的 mysql 表:

+---------------------+--------+
| Timestamp           | Total  |
+---------------------+--------+
| 2012-07-04 05:35:00 |  1.280 | 1.280-1.280 = 0
| 2012-07-04 09:25:00 |  2.173 | 2.173-1.280 = 0.893
| 2012-07-04 09:30:00 |  2.219 | 2.219-1.280 = 0.939
| 2012-07-04 15:00:00 |  7.778 | 7.778-1.280 = 6.498
| 2012-07-04 21:05:00 | 13.032 | 13.032-1.280 = 11.752
| 2012-07-04 22:00:00 | 13.033 | 13.033-1.280 = 11.753
| 2012-07-05 05:20:00 | 13.033 | 13.033-13.033 = 0
| 2012-07-05 07:10:00 | 13.140 | 13.140-13.033 = 0.107
| 2012-07-05 10:15:00 | 14.993 | 14.993-13.033 = 1.960
| 2012-07-05 11:35:00 | 16.870 | 16.870-13.033 = 3.837
+---------------------+--------+

我正在寻找的是一个查询,它确定每个时间间隔的累计每日增长。我试图展示期望的结果以及每一行背后的计算。我已经尝试了几件加入的事情,但不知何故我无法确定每天的起始值是多少。

谢谢。

4

1 回答 1

0

我无法保证此查询的效率,但它确实为您提供了您正在寻找的结果:

SELECT t1.`Timestamp`, t1.`Total`, 
      CASE WHEN t1.`timestamp` =
            (SELECT MIN(t2.`Timestamp`)
             FROM myTable t2 
             WHERE DATE(t2.`Timestamp`)=DATE(t1.`Timestamp`)) 
        THEN 0
        ELSE t1.`Total` - (SELECT MIN(t3.`Total`)
              FROM myTable t3
              WHERE DATE(t3.`Timestamp`)=DATE(t1.`Timestamp`))         
        END AS Diff
FROM myTable t1
ORDER BY `Timestamp`

替代解决方案(我认为更有效)

SELECT  t1.`Timestamp`, t1.`Total`, (t1.`Total` - d1.MinVal) diff
FROM myTable t1 
  INNER JOIN 
     (SELECT DATE(`Timestamp`) ts_date,
             MIN(`Total`) AS MinVal
      FROM myTable
      GROUP BY ts_date) d1
  ON DATE(t1.`Timestamp`) = d1.ts_date
于 2012-08-06T22:46:58.657 回答