我在 MySQL 中使用十进制数据类型创建了一个名为“hours_spent”的字段来存储时间。这些值存储为 1.30、2.30 等...(1 小时 30 分钟、2 小时 30 分钟)。
我想计算各种时间值的总和。
时间总和不是我预期的:1.30 + 2.30 = 3.60,而我预期是 4.00。
我使用了 MySQL 中的 SUM 函数来统计 hours_spent 字段。如果值为 0.30 + 1.50 = 1.80,而我预期为 2.20。
我的第一个错误是使用小数类型而不是时间数据类型,但我无法更改数据类型。
那么,有什么方法可以对时间值求和并得到我预期的结果吗?
谢谢
最佳答案
我在 sqlfiddle 上给你准备了一个演示,如果你想的话,你可以在那里试试:
http://www.sqlfiddle.com/#!2/c9afc/2
以下是查询示例:
select @indexer:=instr(dateasdecimal, '.')
, left(dateasdecimal, @indexer-1) * 60 + substr(dateasdecimal, @indexer+1) as totalMinutes
from testtable;
select @indexer:=instr(dateasdecimal, '.')
, sum(left(dateasdecimal, @indexer-1) * 60 + substr(dateasdecimal, @indexer+1)) as totalMinutes
from testtable;
注意:请不要忘记接受您问题的答案: https://meta.stackexchange.com/a/65088/200585
关于mysql - 有没有办法在 MySQL 中将小数转换为时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588984/