MySQL查询计算行之间的时间差异

时间:2018-11-13 04:30:28

标签: mysql sql

我在有条件的情况下在mysql中查询表有一个问题。

我创建了这样的存储过程:

SELECT A.*, TIMESTAMPDIFF(SECOND,A.start, COALESCE(MIN(B.start), NOW())) AS timespent_in_sec FROM activity_logs A LEFT JOIN  activity_logs B ON  B.user_id = A.user_id AND B.id > A.id WHERE A.user_id = userId AND A.start  >=   startDate  AND  A.start <= endDate GROUP BY A.id, Day(A.start) ORDER BY A.start ASC

其中的userId,startDate和endDate是参数。

所以当我执行以下过程时,结果是:

id      start                   activity            user_id     timespent_in_sec
--------------------------------------------------------------------------------
1       2018-11-12 10:37:53     Login               81          124
2       2018-11-12 10:39:57     1st Break           81          59
3       2018-11-12 10:40:56     1:1 Coaching        81          35
4       2018-11-12 10:41:31     2nd Break           81          76
5       2018-11-12 10:42:47     Logout              81          63384

所以我的目标是停止计算,或者如果它们达到注销活动,则将其设置为0。像这样的东西:

id      start                   activity            user_id     timespent_in_sec
1       2018-11-12 10:37:53     Login               81          124
2       2018-11-12 10:39:57     1st Break           81          59
3       2018-11-12 10:40:56     1:1 Coaching        81          35
4       2018-11-12 10:41:31     2nd Break           81          76
5       2018-11-12 10:42:47     Logout              81          0 // means user has been logout and this will end the computation od timespent in sec

将感谢您的帮助。 预先感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用CASE WHEN表达式。

SELECT A.*, 
      CASE WHEN activity = 'Logout' 
           THEN 0 
           ELSE TIMESTAMPDIFF(SECOND,A.start, COALESCE(MIN(B.start), NOW())) 
       END AS timespent_in_sec
FROM activity_logs A 
LEFT JOIN  activity_logs B ON  B.user_id = A.user_id AND B.id > A.id 
WHERE A.user_id = userId AND A.start >= startDate  AND  A.start <= endDate GROUP BY A.id, Day(A.start) 
ORDER BY A.start ASC