Search code examples
sqlgoogle-bigqueryaverage

How to calculate average time when it is used TIME format in Bigquery?


I'm trying to get the AVG time, but the time format is not supported by the AVG function. I tried with CAST function, like in some posts were explained, but it seems doesn't work anyway. Thanks

WITH october_fall AS
   (SELECT
   start_station_name,
   end_station_name,
   start_station_id,
   end_station_id,
   EXTRACT (DATE FROM started_at) AS start_date,
   EXTRACT(DAYOFWEEK FROM started_at) AS start_week_date,
   EXTRACT (TIME FROM started_at) AS start_time,    
   EXTRACT (DATE FROM ended_at) AS end_date,
   EXTRACT(DAYOFWEEK FROM ended_at) AS end_week_date,    
   EXTRACT (TIME FROM ended_at) AS end_time,
   DATETIME_DIFF (ended_at,started_at, MINUTE) AS total_lenght,
   member_casual
FROM 
   `ciclystic.cyclistic_seasonal_analysis.fall_202010` AS fall_analysis
ORDER BY 
   started_at DESC)
SELECT
   COUNT (start_week_date) AS avg_start_1,
   AVG (start_time) AS avg_start_time_1, ## here is where the problem start
   member_casual
FROM 
   october_fall
WHERE 
   start_week_date = 1
GROUP BY
   member_casual

Solution

  • Try below

    SELECT
       COUNT (start_week_date) AS avg_start_1,
       TIME(
         EXTRACT(hour   FROM AVG(start_time - '0:0:0')), 
         EXTRACT(minute FROM AVG(start_time - '0:0:0')), 
         EXTRACT(second FROM AVG(start_time - '0:0:0'))
       ) as avg_start_time_1
       member_casual
    FROM 
       october_fall
    WHERE 
       start_week_date = 1
    GROUP BY
       member_casual     
    

    Another option would be

    SELECT
       COUNT (start_week_date) AS avg_start_1,
       PARSE_TIME('0-0 0 %H:%M:%E*S', '' || AVG(start_time - '0:0:0')) as avg_start_time_1
       member_casual
    FROM 
       october_fall
    WHERE 
       start_week_date = 1
    GROUP BY
       member_casual