SUM差异落后于时间

时间:2014-01-30 20:17:50

标签: mysql sql

我遇到时间差异的问题。

在数据库中它们是重复记录。例如:

_Status________Information__________Time______
Start(1)  |  heating on 20°C        |  10:00
Start(1)  |  heating on 21°C        |  10:20
Stop(0)   |  Heating                |  11:00
Stop(0)   |  Wait for instructions  |  12:00

记录 A(开始) C(停止)背后的差异是 1小时

当我不使用SUM时,我会得到具有正确时差的行。

查询

SET @end_time=0;

SELECT (TIME_TO_SEC(t2.date) - TIME_TO_SEC(t1.date)) AS difference, t1.date AS start, t2.date AS stop, @end_time:=t2.date

    FROM `heating_history` AS t1

    LEFT JOIN `heating_history`  AS t2 ON t2.date > t1.date and t2.status!=1

    WHERE t1.status=1 and TIME_TO_SEC(t1.date) > TIME_TO_SEC(@end_time)

结果

difference  start                   stop                    @end_time:=t2.date
12703   2014-01-29 07:18:32     2014-01-29 10:50:15     2014-01-29 10:50:15
4079    2014-01-29 13:27:12     2014-01-29 14:35:11     2014-01-29 14:35:11
9839    2014-01-29 16:46:12     2014-01-29 19:30:11     2014-01-29 19:30:11
4810    2014-01-29 21:18:11     2014-01-29 22:38:21     2014-01-29 22:38:21

但是当我想要值的SUM时,我得到了结果。

查询

SET @end_time=0;

SELECT SUM(TIME_TO_SEC(t2.date) - TIME_TO_SEC(t1.date)) AS difference, t1.date AS start, t2.date AS stop, @end_time:=t2.date

FROM `heating_history` AS t1

LEFT JOIN `heating_history`  AS t2 ON t2.date > t1.date and t2.status!=1

WHERE t1.status=1 and TIME_TO_SEC(t1.date) > TIME_TO_SEC(@end_time)

结果

difference  start                   stop                    @end_time:=t2.date
258536  2014-01-29 07:18:32     2014-01-29 10:50:15     2014-01-29 10:50:15

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

你的问题来自于没有指定你想要SUM的内容,因为没有group by子句它只是简化了你拥有的一切。为了确保您只是总结您想要的差异,请以这种方式使用子选择查询。

SELECT SUM(DIFFERENCE),start,stop
FROM
(
SELECT (TIME_TO_SEC(t2.date) - TIME_TO_SEC(t1.date)) AS difference, t1.date AS start, t2.date AS stop, @end_time:=t2.date
FROM `heating_history` AS t1
LEFT JOIN `heating_history`  AS t2 ON t2.date > t1.date and t2.status!=1
WHERE t1.status=1 and TIME_TO_SEC(t1.date) > TIME_TO_SEC(@end_time) and DATE(t1.date)=DATE_SUB(CURDATE(), INTERVAL 1 day)) as MyQuery

您不能只在查询中抛出SUM并希望获得正确的结果。您需要指定GROUP BY子句或使用子选择SUM您的正确结果。