Finding the median of a time type column in MySQL

39 views Asked by At

So I have a table q4_2022_data where each record is one bike ride, one of the columns in this table called ride_time is the time of each ride. I am using MySQL and tried using PERCENTILE_DISC to find the median value for this column but obviously didn't work.

WITH RankedRides AS (
  SELECT
    ride_time,
    ROW_NUMBER() OVER (ORDER BY ride_time) AS row_num,
    COUNT(*) OVER () AS total_rows
  FROM
    q4_2022_data
)

SELECT
  SEC_TO_TIME(
    AVG(TIME_TO_SEC(ride_time))
  ) AS median_ride_time
FROM (
  SELECT
    ride_time,
    row_num,
    total_rows
  FROM
    RankedRides
) AS subquery
WHERE
  row_num BETWEEN (total_rows DIV 2) + 1 AND (total_rows DIV 2) + 2;

This is the query I have come up with, it gives me a value of 00:08:00.0000, I tried this with the other quarter tables (q1, q2, q3) to check and realised that every single value was a whole number. I was given results 00:10:00.0000, 00:11:00.0000 . Is there anything I can do so that I get the exact median and can anyone figure out why it's being rounded. Any help is appreciated thank you.

0

There are 0 answers