如何取小时的平均持续时间; SQL中的分钟?

时间:2013-10-04 15:20:16

标签: sql oracle datetime oracle11g sqlplus

我需要取平均值表中的一列。它的格式为Hrs和Mins。

查询

select DURATIONHM from TableT where nownum < 9.

输出

DURATIONHM
--------------------------------
5 hrs 5 min
2 hrs 20 min
1 hrs 29 min
1 hrs 45 min
4 hrs 10 min
3 hrs 35 min
1 min
32 min
1 hrs 16 min

9 rows selected.

必填输出。

我需要取平均值DURATIONHM

select avg(DURATIONHM) as DurationTime from TableT

错误

ERROR at line 1:
ORA-01722: invalid number

我需要的输出Hour & Minute.

1 个答案:

答案 0 :(得分:3)

如果您使用 regexp_substr ,那就不错了:

CREATE TABLE tablet (durationhm VARCHAR2(20));

INSERT INTO tablet VALUES ('5 hrs 5 min');
INSERT INTO tablet VALUES ('2 hrs 20 min');
INSERT INTO tablet VALUES ('1 hrs 29 min');
INSERT INTO tablet VALUES ('1 hrs 45 min');
INSERT INTO tablet VALUES ('4 hrs 10 min');
INSERT INTO tablet VALUES ('3 hrs 35 min');
INSERT INTO tablet VALUES ('1 min');
INSERT INTO tablet VALUES ('32 min');
INSERT INTO tablet VALUES ('1 hrs 16 min');

COMMIT;

SELECT (NVL(regexp_substr(durationhm, '([0-9]+) hrs', 1, 1, NULL, 1), 0) * 60
        + NVL(regexp_substr(durationhm, '([0-9]+) min', 1, 1, NULL, 1), 0)) AS number_of_minutes
  FROM tablet;

NUMBER_OF_MINUTES      
---------------------- 
305                    
140                    
89                     
105                    
250                    
215                    
1                      
32                     
76                

SELECT AVG(NVL(regexp_substr(durationhm, '([0-9]+) hrs', 1, 1, NULL, 1), 0) * 60
        + NVL(regexp_substr(durationhm, '([0-9]+) min', 1, 1, NULL, 1), 0)) AS average_time
  FROM tablet;

AVERAGE_TIME           
---------------------- 
134,777777777777777777777777777777777778

检查SQLFiddle:http://sqlfiddle.com/#!4/ad58c/1

编辑:抱歉,没看到您也希望以#of_hours小时#of_minutes分钟的格式获得答案。它变得丑陋,但有效(目前还不确定如何编写看起来更好的查询):

SELECT 
    CASE
      WHEN average_time >= 60 THEN trunc(average_time / 60) || ' hrs'
                                    || 
                                      CASE
                                        WHEN MOD(average_time, 60) = 0 THEN NULL
                                        ELSE ' ' || MOD(average_time, 60) || ' min'
                                      END
      ELSE MOD(average_time, 60) || ' min'
    END AS average_formatted
  FROM (
    SELECT TRUNC(AVG(NVL(regexp_substr(durationhm, '([0-9]+) hrs', 1, 1, NULL, 1), 0) * 60
          + NVL(regexp_substr(durationhm, '([0-9]+) min', 1, 1, NULL, 1), 0))) AS average_time
      FROM tablet
);

嗯,想出了另一种可能性(尽管很难看):

SELECT
 RTRIM(DECODE(TRUNC(average_time / 60), 0, NULL, trunc(average_time / 60) || ' hrs ') ||
    DECODE(MOD(average_time, 60), 0, NULL, MOD(average_time, 60) || ' min'))
      AS average_formatted
  FROM (
    SELECT TRUNC(AVG(NVL(regexp_substr(durationhm, '([0-9]+) hrs', 1, 1, NULL, 1), 0) * 60
          + NVL(regexp_substr(durationhm, '([0-9]+) min', 1, 1, NULL, 1), 0))) AS average_time
      FROM tablet
);