0

I need to take average of one of the column in table. it has duration in format of Hrs and Mins.

Query

select DURATIONHM from TableT where nownum < 9.

Output

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.

Required Output.

I need to take average DURATIONHM

select avg(DURATIONHM) as DurationTime from TableT

Error

ERROR at line 1:
ORA-01722: invalid number

Output I need in also Hour & Minute.

4

1 回答 1

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 hrs #of_minutes min 格式获得答案。它变得丑陋,但有效(目前不确定如何编写看起来更好的查询):

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
);
于 2013-10-04T15:49:45.020 回答