Finding median in mysql using group_concat
Query:
SELECT IF(count%2=1, SUBSTRING_INDEX(substring_index(data_str,",",pos),",",-1), (SUBSTRING_INDEX(substring_index(data_str,",",pos),",",-1) + SUBSTRING_INDEX(substring_index(data_str,",",pos+1),",",-1))/2) as median FROM (SELECT group_concat(val order by val) data_str, CEILING(count(*)/2) pos, count(*) as count from data)temp;
Explanation:
Sorting is done using order inside the group_concat function
Position (pos) and Total number of elements (quantity) identified. CEILING for position determination helps us use the substring_index function in the next steps.
Based on the count, an even or odd number of values ββis determined.
- Odd values: directly select the element belonging to pos using substring_index.
- Even values: find the element belonging to pos and pos + 1, then add them and divide by 2 to get the median.
Finally, the median is calculated.
subrat mishra
source share