因此,我得到了一组类似于以下内容的结果:
SELECT User_ID, StartTime, EndTime, TIMEDIFF(EndTime, StartTime) AS TimeDiff FROM MyTable ------------------------------------------------------------------ | User_ID | StartTime | EndTime | TimeDiff | ------------------------------------------------------------------ | 1 | 2010-11-05 08:00:00 | 2010-11-05 09:00:00 | 01:00:00 | ------------------------------------------------------------------ | 1 | 2010-11-05 09:00:00 | 2010-11-05 10:00:00 | 01:00:00 | ------------------------------------------------------------------ | 2 | 2010-11-05 06:30:00 | 2010-11-05 07:00:00 | 00:30:00 | ------------------------------------------------------------------ | 2 | 2010-11-05 07:00:00 | 2010-11-05 09:00:00 | 02:00:00 | ------------------------------------------------------------------ | 2 | 2010-11-05 09:00:00 | 2010-11-05 10:00:00 | 01:00:00 | ------------------------------------------------------------------
现在,我需要按User_ID和SUM()TimeDiff对结果进行分组。如果我添加一个GROUP BY子句,则它不是SUM()TimeDiff(并且我不希望这样)。如何SUM()为每个用户设置TimeDiff?
User_ID
SUM()
GROUP BY
使用:
SELECT t.user_id, SEC_TO_TIME(SUM(TIME_TO_SEC(t.endtime) - TIME_TO_SEC(t.starttime))) AS timediff FROM MYTABLE t GROUP BY t.user_id
脚步:
基于示例数据,我只是建议:
SELECT t.user_id, TIMEDIFF(MIN(t.startdate), MAX(t.enddate)) AS timediff FROM MYTABLE t GROUP BY t.user_id
注意:如果您使用日期时间,则此代码中有一个错误。TIME_TO_SEC仅转换时间部分,因此如果时钟经过午夜,则最终会带来很大的负面影响。使用UNIX_TIMESTAMP代替进行总和。另外,SEC_TO_TIME的最大值超过3020399秒,例如SELECT TIME_TO_SEC(SEC_TO_TIME(3020400));如果您看到此值838:59:59,则您已达到最大值,可能只需要除以3600就可以显示小时数。