简体   繁体   English

如何计算Mysql中一行的中位数?

[英]How to calculate the median of a row in Mysql?

I am new to sql and have been struggling about nan-median, for example, I have a table with three (million) rows, each with ten numbers (or null): 我是sql的新手并且一直在努力研究nan-median,例如,我有一个包含三(百万)行的表,每行有十个数字(或null):

row1: 1,2,3,null,4,5,6,7,8,9
----------
row2: 2,4,null,6,8,2,1,0,9,10
----------
row3: 1,1,1,1,null,7,2,9,9,9
----------

How to get the nan-median of each row ? 如何获得每 的中位数

According to your question, If you have 10 columns that you want to calculate. 根据您的问题,如果您想要计算10列。 The trick is to avoid the null values with Coalesce function. 诀窍是使用Coalesce函数避免空值。 Use this logic: 使用此逻辑:

Select (coalesce(Col1, 0) + coalesce(Col2, 0) + coalesce(Col3, 0)+ coalesce(Col4, 0)+coalesce(Col5, 0)+coalesce(Col6, 0)+coalesce(Col7, 0)+coalesce(Col8, 0)+coalesce(Col9, 0)+.coalesce(Col10, 0))/10 
from yourtable
select(
   (select MAX(cols) from 
    (select TOP 50 PERCENT cols from table ORDER BY cols) )  
        + 
          (select MIN(cols) from 
            (select TOP 50 PERCENT cols from table ORDER BY cols DESC) ) 
     ) / 2  
Median

Select max of first 50% rows by sorting the rows in asc which should be the median in case if column count is even. 通过对asc中的行进行排序来选择前50%行的最大值,如果列数为偶数,则应该是中位数。 Select min of next 50% rows by ordering the rows in desc, in case if column count is even, this will be median or else max of (firsthalf+min of secondhalf)/2 will be the median. 通过在desc中对行进行排序来选择下一个50%行的最小值,以防列数为偶数,这将是中位数,否则最大值(firsthalf + min of secondhalf)/ 2将是中位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM