使用仅限SQL 解决方案将"1 h 15 min"
之类的字符串转换为75
是否可行?
修改
在某些情况下,字符串的格式也可以是"1 h"
或"15 min"
,但它永远不会包含天和秒。
答案 0 :(得分:7)
简短的黑客:
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;
(仅适用于时间<24h)
答案 1 :(得分:3)
鉴于此测试表
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
答案 2 :(得分:2)
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