MySQL - 如何求和时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1329458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:57:54  来源:igfitidea点击:

MySQL - How to SUM times?

mysql

提问by John M

I have a table that contains date-time values in this format:

我有一个包含以下格式的日期时间值的表:

START

开始

1/13/2009 7:00:00AM

1/13/2009 7:00:00AM

END

结尾

1/13/2008 2:57:00PM

2008/1/13 下午 2:57:00

I use the 'str to date' function to convert these into a date-time format.

我使用“str to date”函数将这些转换为日期时间格式。

How do I calculate a difference between them? And then sum it all up so that it displays in total hours (ie total hours for week is 40:53).

我如何计算它们之间的差异?然后将其汇总起来,以总小时数显示(即一周的总小时数为 40:53)。

I was trying the timediff function but the results don't sum.

我正在尝试 timediff 函数,但结果不求和。

采纳答案by Eric Petroelje

Try looking into UNIX_TIMESTAMPand SEC_TO_TIME.

尝试查看UNIX_TIMESTAMPSEC_TO_TIME

You would sum up the differences between the timestamps, then use that value (would be in milliseconds) to get the time:

您将总结时间戳之间的差异,然后使用该值(以毫秒为单位)来获取时间:

SELECT SEC_TO_TIME(time_milis / 1000)
FROM (
   SELECT SUM(UNIX_TIMESTAMP(date1) - UNIX_TIMESTAMP(date2)) as time_milis
   FROM table
)

回答by vhan

I think you have to use this code... it works :)

我认为您必须使用此代码...它有效:)

SELECT  
  SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) ) AS total_time  
FROM time_table;

回答by Jason

Check out the MySQL DateDiff Function

查看MySQL DateDiff 函数

SELECT SUM(DATEDIFF(endtime, starttime)) 
FROM somerecordstable
WHERE starttime > '[some date]' AND endtime <= '[some date]'

You could also try:

你也可以试试:

SELECT SUM(TIMEDIFF(endtime, starttime)) 
FROM somerecordstable
WHERE starttime > '[some date]' AND endtime <= '[some date]'

I haven't tested the second one, but I know the first one should work.

我还没有测试第二个,但我知道第一个应该有效。

回答by dnagirl

SELECT some_grouping_column, SUM(TIMEDIFF(datecol1,datecol2)) as tot_time
FROM my_table
GROUP BY some_grouping_column;

回答by Eevee

Use TIMEDIFF().

使用TIMEDIFF().

SUM(TIMEDIFF(end, start))