我似乎无法弄清楚。我有一些时间格式为00:00:00(hh:mm:ss)的行,我需要计算完成一项任务所需的总时间。 我无法汇总这些数据。有人可以建议将其转换为我可以求和的格式的方法,还是可以计算出任务总时间的方法。 感谢您的协助。这在Oracle数据库中。
答案 0 :(得分:1)
将您的时间字符串转换为日期,并减去午夜的等效日期,以便为您提供一天的一部分数字。然后,您可以求和该数字并将其转换为间隔:
Oracle设置:
CREATE TABLE test_data( value ) AS
SELECT '01:23:45' FROM DUAL UNION ALL
SELECT '12:34:56' FROM DUAL UNION ALL
SELECT '23:45:00' FROM DUAL;
查询:
SELECT NUMTODSINTERVAL(
SUM( TO_DATE( value, 'HH24:MI:SS' ) - TO_DATE( '00:00:00', 'HH24:MI:SS' ) ),
'DAY'
) AS total_time_taken
FROM test_data;
输出:
| TOTAL_TIME_TAKEN | | :---------------------------- | | +000000001 13:43:41.000000000 |
db <>提琴here
更新,包括持续时间超过23:59:59
的时间。
Oracle设置:
CREATE TABLE test_data( value ) AS
SELECT '1:23:45' FROM DUAL UNION ALL
SELECT '12:34:56' FROM DUAL UNION ALL
SELECT '23:45:00' FROM DUAL UNION ALL
SELECT '48:00:00' FROM DUAL;
查询:
SELECT NUMTODSINTERVAL(
SUM(
DATE '1970-01-01'
+ NUMTODSINTERVAL( SUBSTR( value, 1, HM - 1 ), 'HOUR' )
+ NUMTODSINTERVAL( SUBSTR( value, HM + 1, MS - HM - 1 ), 'MINUTE' )
+ NUMTODSINTERVAL( SUBSTR( value, MS + 1 ), 'SECOND' )
- DATE '1970-01-01'
),
'DAY'
) AS total_time
FROM (
SELECT value,
INSTR( value, ':', 1, 1 ) AS HM,
INSTR( value, ':', 1, 2 ) AS MS
FROM test_data
);
输出:
| TOTAL_TIME | | :---------------------------- | | +000000003 13:43:41.000000000 |
db <>提琴here
更好的是,如果您更改表以将持续时间作为间隔而不是字符串来保存,那么一切将变得更加简单:
Oracle设置:
CREATE TABLE test_data( value ) AS
SELECT INTERVAL '1:23:45' HOUR TO SECOND FROM DUAL UNION ALL
SELECT INTERVAL '12:34:56' HOUR TO SECOND FROM DUAL UNION ALL
SELECT INTERVAL '23:45:00' HOUR TO SECOND FROM DUAL UNION ALL
SELECT INTERVAL '48:00:00' HOUR TO SECOND FROM DUAL;
查询:
SELECT NUMTODSINTERVAL(
SUM( DATE '1970-01-01' + value - DATE '1970-01-01' ),
'DAY'
) AS total_time
FROM test_data;
输出:
| TOTAL_TIME | | :---------------------------- | | +000000003 13:43:41.000000000 |
db <>提琴here