【问题标题】:MySQL Adding Timestamp Values, Adding Resultset, and Grouping by DateMySQL 添加时间戳值、添加结果集和按日期分组
【发布时间】:2013-11-01 04:11:17
【问题描述】:

以下查询以 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

【问题讨论】:

  • 朋友帮我解答:SELECT DATE(start_time) AS Date, 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 DATE(start_time)

标签: mysql sql


【解决方案1】:

如果您有列日期,则无需创建GROUP BY start_time, end_time(我建议您创建列日期以对“时间差异”进行分组)。
这是我的例子:
我的表(命名时间)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    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 列作为与开始时间和结束时间不同的列。
你没有给我你表的结构,所以我看不清楚你的问题。

更新:
我想你有一张这样的桌子:
可能您的问题是: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;

它将返回:

或者如果您运行此查询:

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

它会返回这个:

【讨论】:

  • Oki,表结构就是user_id、start_time、end_time。每天有多个条目,因此 2013-10-01 可能有 20 个条目。
  • 您的意思是20 entries per day per user(20/天/用户或20/用户/天)还是20 entries for all user(20/天)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
相关资源
最近更新 更多