I'm trying to create an aggregated function MEDIAN() in MySQL like MIN(), MAX(), AVG() which takes the input the column name or string that has concatenated values of the desired column.
I'm having trouble understanding the limitations of MySQL custom functions & would be really helpful if some can help me find out how this is done.
Example:
MySQL table has 2 columns (ID, num)
+----+-----+
| id | num |
+----+-----+
| 1 | 5 |
| 1 | 6 |
| 1 | 7 |
| 2 | 1 |
| 2 | 3 |
| 2 | 5 |
+----+-----+
SELECT id, MEDIAN(num) as median
FROM table
GROUP BY id;
OR
SELECT id, MEDIAN(GROUP_CONCAT(num SEPARATOR ',') as median
FROM table
GROUP BY id;
Expected Output is
+----+--------+
| id | median |
+----+--------+
| 1 | 6 |
| 2 | 3 |
+----+--------+
User defined aggregate stored functions were added in MariaDB-10.3.3
MySQL can do aggregate functions however not in SQL. They need a UDF (shared library implemenation)