按日期查找值的变化

时间:2015-05-29 17:32:40

标签: mysql sql

我有这样的表:

datetime               |  value
-----------------------------------
2015-05-01 12:23:41    |  12 
2015-05-01 22:13:11    |  21 
2015-05-02 9:13:41     |  23 
2015-05-02 17:23:41    |  32 

每天随机时间约有100个条目。 我需要计算以下内容:

  1. 每日增加 - 今天和第一次进入之间的差异 昨天(每天)的进入
  2. 每日平均增加 - 今日平均值与平均值之间的差异 昨天(每天)的价值
  3. 如何编写SQL查询以获取这些值?

2 个答案:

答案 0 :(得分:1)

我要做的是获取每个日期的第一个条目是按日期部分分组,并获得这样的最短日期时间:

SELECT DATE(dateCol), MIN(dateCol)
FROM myTable
GROUP BY DATE(dateCol);

这可以帮助您查看以下结果:

| 2015-05-01 | 2015-05-01 12:23:41 |

获得这些值后,您可以将这两个表连接在一起,使每个日期与前一个相邻,如下所示:

SELECT t1.firstDate, t2.secondDate
FROM(
  SELECT DATE(dateCol) AS wholeDate, MIN(dateCol) AS firstDate
  FROM myTable
  GROUP BY DATE(dateCol)) t1
JOIN(
  SELECT DATE(dateCol) AS wholeDate, MIN(dateCol) AS secondDate
  FROM myTable
  GROUP BY DATE(dateCol)) t2 ON t1.wholeDate < t2.wholeDate AND t2.wholeDate = (SELECT MIN(DATE(dateCol)) FROM myTable WHERE DATE(dateCol) > DATE(t1.wholeDate));

然后,您所要做的就是调整您的select语句以获得差异。您还必须联接回原始表以获取值:

SELECT t1.firstDate, t2.secondDate, (s.value - f.value) AS difference
FROM(
  SELECT DATE(dateCol) AS wholeDate, MIN(dateCol) AS firstDate
  FROM myTable
  GROUP BY DATE(dateCol)) t1
JOIN(
  SELECT DATE(dateCol) AS wholeDate, MIN(dateCol) AS secondDate
  FROM myTable
  GROUP BY DATE(dateCol)) t2 ON t1.wholeDate < t2.wholeDate AND t2.wholeDate = (SELECT MIN(DATE(dateCol)) FROM myTable WHERE DATE(dateCol) > DATE(t1.wholeDate))
JOIN myTable f ON f.dateCol = t1.firstDate
JOIN myTable s ON s.dateCol = t2.secondDate;

对于第二部分,您需要计算每个日期的平均值,然后以类似的方式加入表格,以查看日期与日期之间的差异。

以下是SQL Fiddle示例,此处的similar question也可能对您有所帮助。

答案 1 :(得分:-1)

http://sqlfiddle.com/#!9/8cc73/1

SELECT DATE(`datetime`), MAX(`value`)-MIN(`value`)
FROM table1
GROUP BY DATE(`datetime`)

SELECT AVG(`increase`)
FROM (
SELECT DATE(`datetime`), MAX(`value`)-MIN(`value`) as increase
FROM table1
GROUP BY DATE(`datetime`)
  ) as t