是否可以将字符串转换"1 h 15 min"
为仅75
使用SQL的解决方案?
编辑:
该字符串也可能是格式"1 h"
或"15 min"
在某些情况下,但它从不包含天数和秒数。
简短的破解:
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;
(仅适用于 < 24 小时的时间)
鉴于此测试表
create table a(a varchar(20));
insert into a values ('1 h 15 min'), ('1 h'), ('15 min');
这个查询
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
返回
b
75
60
15
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