MySQL按日期添加时间戳值,添加结果集和分组

时间:2013-10-23 03:33:10

标签: mysql sql

以下查询返回start_time和end_time中的时间戳,以及每个时间戳之间的差异(以秒/ 60为单位)。我也算了15天,因为总数需要是“滚动总数”。每天都有多个时间戳。

我想要做的是为每一天添加总计“时间差异”,并按如下方式返回以下日期:

  

10-08-2013 - 小时:分钟:秒

     

10-09-2013 - 小时:分钟:秒

SELECT start_time, end_time, 
SUM(TIMESTAMPDIFF(second, start_time, end_time) /60) as `Time Diff`
FROM time
WHERE start_time >= DATE_SUB(NOW(), INTERVAL 15 DAY)
AND user_id = 'xx'
GROUP BY start_time, end_time

1 个答案:

答案 0 :(得分:1)

如果您有一个列日期,则无需进行GROUP BY start_time, end_time(我建议您创建列日期以分组'time diff')。
这是我的例子:
我的桌子(命名时间)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    date   |     starttime       |       endtime       |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2013-10-23 | 2013-10-23 08:00:00 | 2013-10-23 16:30:00 |
2013-10-24 | 2013-10-24 08:30:00 | 2013-10-24 17:00:00 |

这是我的查询,显示启动时间和结束时间之间的不同时间:

SELECT *, TIMEDIFF(endtime,starttime) AS duration FROM time

它将返回:

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    date   |     starttime       |       endtime       | duration |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2013-10-23 | 2013-10-23 08:00:00 | 2013-10-23 16:30:00 | 08:30:00 |
2013-10-24 | 2013-10-24 08:30:00 | 2013-10-24 17:00:00 | 08:30:00 |

如果您的date列与starttime和endtime不同,那就是这样。
你没有给我你桌子的结构,所以我不能清楚地看到你的问题。

更新:
我想你有一张这样的桌子: table data
可能你的问题是:calculate the time between starting time and ending time from a day of a user that the user could start and stop in anytime (at that day) 我运行此查询来执行此操作:

SELECT *, TIMEDIFF(MAX(end),MIN(start)) AS duration FROM time
GROUP BY user_id, date 
ORDER BY date ASC;

它将返回此:
result 1
或者如果您运行此查询:

SELECT 
user_id,
MIN(start) AS start, 
MAX(end) AS end, 
TIMEDIFF(MAX(end),MIN(start)) AS duration 
FROM time
GROUP BY user_id, date 
ORDER BY date ASC

它将返回此:
result 2