1. 程式人生 > 實用技巧 >MySQL中位數計算方法

MySQL中位數計算方法

在網上搜到的一種演算法是利用自增長變數進行排序,然後再根據位置序號取。感覺有些複雜了,還是group_concat來的省事些

1. 按順序聚合,逗號分隔,並計數

group_concat( number order by number asc)

2. 根據逗號拆分,判斷奇偶數去擷取中間位置的那個數

具體程式碼如下:

SELECT 
            doctor_name doctor,  -- 分組
	    count(1) patientNum,  -- 總數
	    group_concat(dnt order by dnt asc),
	    substring_index(SUBSTRING_INDEX(group_concat(dnt order by dnt asc),',',(count(1)+1) div 2),',',-1)  dnt,
	    case when count(1)%2=1 then substring_index(SUBSTRING_INDEX(group_concat(dnt order by dnt asc),',',(count(1)+1) div 2),',',-1) else (substring_index(SUBSTRING_INDEX(group_concat(dnt order by dnt asc),',',(count(1)+2) div 2),',',-1) + 
									    substring_index(SUBSTRING_INDEX(group_concat(dnt order by dnt asc),',',count(1) div 2),',',-1))/2
           end mid_dnt
FROM
(
                SELECT distinct doctor_name, record_id, dnt
                from rp_green_channel_patient_detaile
                where dnt is not null
                        AND visit_day >= '2020-03-30' 
                        AND visit_day <= '2020-06-27' 
                
) AS a 
group by doctor_name