【问题标题】:Is any way to convert decimal to time in MySQL?有什么方法可以在 MySQL 中将十进制转换为时间?
【发布时间】:2012-11-27 16:46:16
【问题描述】:

我在 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。

我的第一个错误是使用十进制类型而不是时间数据类型,但我无法更改数据类型。

那么,有什么方法可以对时间值求和并得到我期望的结果?

谢谢

【问题讨论】:

  • 好问题!我会知道如何使用 PHP 来做到这一点,但要明确的是,您希望这些计算直接在 mysql 中完成吗?我很想听听答案..
  • 您可能需要为此编写自定义代码。
  • 好的。我从 mysql 获取数据并在 PHP 中执行。 PHP中是否有任何预定义的函数?或者是什么方法?

标签: mysql date typeconverter


【解决方案1】:

我在 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

【讨论】:

    【解决方案2】:

    要将小数转换为秒,您可以这样:

    truncate(hours_spent,0)*60+(hours_spent-truncate(hours_spent,0))*100
    

    然后你就可以轻松地计算总和了。然后您可以使用以下方法将秒数转换为十进制格式:

    truncate(seconds/60,0)+truncate(mod(seconds, 60)/100,2)
    

    【讨论】:

      【解决方案3】:

      您始终可以将小数转换为字符串,转换为时间,然后使用 time_to_sec 将该时间相加,并使用 sec_to_time 生成格式化时间。当然,以不同的方式存储这些时间会更好,即使它涉及转换整个数据集。

      SELECT sec_to_time(sum(time_to_sec(goodTime))) FROM (   
          SELECT CAST(badTime AS TIME) AS goodTime FROM ( 
              SELECT REPLACE(badTime, '.', ':') AS badTime FROM (
                  SELECT CAST(badTime AS dec(4,2)) AS badTime FROM (
                      SELECT 1.3 AS badTime 
                      UNION select 2.3 
                  ) z
              ) y
          ) x
      ) w
      

      【讨论】:

        猜你喜欢
        • 2011-07-02
        • 2017-09-03
        • 2015-03-12
        • 1970-01-01
        • 2016-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多