I am trying to calculate the mean + median on a table and I am grouping the result. Since there is no built in unction for the median calculation I am referencing this to calculate the median. Simple way to calculate median with MySQL
My current query is the following:
SELECT DATE(t1.dateCreated) AS date_created,
ROUND(AVG(t1.processTime), 2) AS average_process_time,
ROUND(AVG(t1.time2), 2) AS average_time2,
(SELECT AVG(dd.processTime)
FROM (
SELECT d.processTime, @rownum := @rownum + 1 as `row_number`, @total_rows := @rownum
FROM table1 d,
(SELECT @rownum := 0) r
WHERE d.dateCreated >= '2021-06-30'
AND d.dateCreated <= '2021-07-02'
ORDER BY d.processTime
) as dd
WHERE dd.row_number IN (FLOOR((@total_rows + 1) / 2), FLOOR((@total_rows + 2) / 2))) as median_processTime,
(SELECT AVG(dd.time2)
FROM (
SELECT d.time2, @rownum := @rownum + 1 as `row_number`, @total_rows := @rownum
FROM table1 d,
(SELECT @rownum := 0) r
WHERE d.dateCreated >= '2021-06-30'
AND d.dateCreated <= '2021-07-02'
ORDER BY d.time2
) as dd
WHERE dd.row_number IN (FLOOR((@total_rows + 1) / 2), FLOOR((@total_rows + 2) / 2))) as median_time2
FROM table1 t1
WHERE t1.dateCreated >= '2021-06-30'
AND t1.dateCreated <= '2021-07-02'
GROUP BY DATE(t1.dateCreated)
ORDER BY DATE(t1.dateCreated)
But My median calculations are not being compute correctly. Also can this query be optimized?