Mysql,总计每天的TimeDiff。仅包括大于2分钟的TimeDiff

时间:2016-11-17 08:18:46

标签: mysql

我喜欢总结每天的TIMEDIFF总数。它应该加上大于2分钟(00:02:00)的所有TIMEDIFF。而且如果Timediff为0或者会话表一天没有行,那么它也应该说0.我试图显示会话统计数据,看下面的结果。

表“会话”:

dt                   session_id
2016-11-15 11:25:00  1
2016-11-15 11:21:04  1
2016-11-15 11:20:00  1
2016-11-15 09:37:00  2
2016-11-15 09:27:00  2
2016-11-14 21:37:00  3
2016-11-14 21:33:10  3
2016-11-14 21:31:00  3
2016-11-14 16:05:00  4
2016-11-14 16:02:00  4
2016-11-14 10:31:25  5
2016-11-14 10:31:00  5
2016-11-11 16:30:00  5
2016-11-11 16:25:00  5

表“日期”

date             
2016-11-18
2016-11-17
2016-11-16
2016-11-15
2016-11-14
2016-11-13
2016-11-12
2016-11-11

这就是我喜欢的结果:

date         totalTime
2016-11-18   0
2016-11-17   0
2016-11-16   0
2016-11-15   00:15:00
2016-11-14   00:09:00
2016-11-13   0
2016-11-12   0
2016-11-11   00:05:00

这是我目前的查询:

SELECT date.*, 

    SUM(SELECT 
        TIME_TO_SEC(TIMEDIFF(MAX(done_time),MIN(done_time)))
    FROM sessions
    WHERE DATE(sessions.dt) = date.date
        AND session_id IS NOT NULL
    GROUP BY session_id
    HAVING TIMEDIFF(MAX(dt),MIN(dt)) > "00:02:00"
    ) AS activity

FROM date
WHERE (date.date BETWEEN "2016-11-17" AND "2016-10-17")
ORDER BY DATE(date.date) DESC

抱歉,但我无法让它工作

1 个答案:

答案 0 :(得分:0)

SELECT    sq.date,
          SEC_TO_TIME(SUM(TIME_TO_SEC(sq.totalTime))) AS totalTime
FROM      (SELECT   dt.date AS date,
                    IF(MINUTE(TIMEDIFF(MAX(s.dt), MIN(s.dt)))>2, TIMEDIFF(MAX(s.dt), MIN(s.dt)), 0) as totalTime
            FROM    date as dt
                    LEFT OUTER JOIN sessions as s ON dt.date = DATE(s.dt)
            GROUP BY    dt.date, s.session_id
            ORDER BY    dt.date) as sq
GROUP BY  sq.date;