简体   繁体   English

MySQL:如何将“1小时15分钟”之类的字符串转换为75?

[英]MySQL: How can I convert a string like “1 h 15 min” into 75?

Is it posssible to convert a string like "1 h 15 min" into 75 with a SQL only solution? 使用仅SQL解决方案将"1 h 15 min"类的字符串转换为75是否可行?

Edit: 编辑:

The string may also be in the format "1 h" or "15 min" in some cases, but it never contains days and seconds. 在某些情况下,字符串的格式也可以是"1 h""15 min" ,但它永远不会包含天和秒。

Short hack: 短暂的黑客:

SET @ugly_time = '1h 2min';
SELECT TIME_TO_SEC(
    COALESCE(
        STR_TO_DATE(@ugly_time, '%Hh %imin'),
        STR_TO_DATE(@ugly_time, '%imin')
    )
) AS seconds;

(works only for times < 24h) (仅适用于<24h的时间)

Given this test table 鉴于此测试表

create table a(a varchar(20));
insert into a values ('1 h 15 min'), ('1 h'), ('15 min');

this query 这个查询

select
time_to_sec(str_to_date(a, '%l h %i min')) / 60 b
from a
having b is not null 
union all 
select
time_to_sec(str_to_date(a, '%i min')) / 60 b
from a
having b is not null 

returns 回报

b
75
60
15

SQLFiddle appears to be down at the moment and I don't have a MySQL instance to hand so I've written this in SQL Server however it should translate with little issue SQLFiddle目前似乎已经关闭了,我没有一个MySQL实例可供使用,所以我在SQL Server中编写了这个,但是它应该在几乎没有问题的情况下进行翻译

DECLARE @t table (
   horribly_formatted_time varchar(20)
)

INSERT INTO @t (horribly_formatted_time)
  VALUES ('1 h 15 min')
       , ('15 h 59 min')
       , ('25 h 1 min')
       , ('1 h')
       , ('15 min')



SELECT horribly_formatted_time
     , hours
     , minutes
     , (Cast(hours As int) * 60) + Cast(minutes As int) As total_minutes
FROM   (
        SELECT horribly_formatted_time
             , SubString(remove_the_min, 0, separator) As hours
             , SubString(remove_the_min, separator + 3, 20) As minutes
        FROM   (
                SELECT horribly_formatted_time
                     , remove_the_min
                     , CharIndex(' h ', remove_the_min) As separator
                FROM   (
                        SELECT horribly_formatted_time
                             , Replace(consistant_format, ' min', '') As remove_the_min
                        FROM   (
                                  SELECT horribly_formatted_time
                                       , CASE
                                           WHEN horribly_formatted_time NOT LIKE '% min' THEN horribly_formatted_time + ' 0 min'
                                           WHEN horribly_formatted_time NOT LIKE '% h %' THEN '0 h ' + horribly_formatted_time
                                           ELSE horribly_formatted_time
                                         END As consistant_format
                                  FROM   @t
                                 ) As w
                       ) As x
               ) As y
       ) As z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM