MySQL:计算按列分组的中值

nvbavucw  于 2023-01-29  发布在  Mysql
关注(0)|答案(1)|浏览(140)

我有下表:

+------------+-------+
| SchoolName | Marks |
+------------+-------+
| A          |    71 |
| A          |    71 |
| A          |    71 |
| B          |   254 |
| B          |   135 |
| B          |   453 |
| B          |   153 |
| C          |   453 |
| C          |   344 |
| C          |   223 |
| B          |   453 |
| D          |   300 |
| D          |   167 |
+------------+-------+

以下是按学校名称分组的平均分数:

+------------+------------+
| SchoolName | avg(Marks) |
+------------+------------+
| A          |    71.0000 |
| B          |   289.6000 |
| C          |   340.0000 |
| D          |   233.5000 |
+------------+------------+

https://www.db-fiddle.com/f/5t7N3Vx8FSQmwUJgKLqjfK/9
然而,我想计算的不是平均数,而是按学校名称分组的分数中位数。
我在用,

SELECT AVG(dd.Marks) as median_val
FROM (
SELECT d.Marks, @rownum:=@rownum+1 as `row_number`, @total_rows:=@rownum
  FROM tablename d, (SELECT @rownum:=0) r
  WHERE d.Marks is NOT NULL
  ORDER BY d.Marks
) as dd
WHERE dd.row_number IN ( FLOOR((@total_rows+1)/2), FLOOR((@total_rows+2)/2) );

来计算整个"分数"列的平均值,但我不知道如何针对每个学校分别进行计算。

mf98qq94

mf98qq941#

您的查询使用用户变量来计算行号,这使得处理分区变得更加复杂。由于您使用的是MySQL 8.0,我建议您使用窗口函数。
这将使您接近您的预期:

select 
    SchoolName, 
    avg(Marks) as median_val
from (
select 
    SchoolName,
    Marks, 
    row_number() over(partition by SchoolName order by Marks) rn,
    count(*) over(partition by SchoolName) cnt
  from tablename
) as dd
where rn in ( FLOOR((cnt + 1) / 2), FLOOR( (cnt + 2) / 2) )
group by SchoolName

算法保持不变,但是我们在具有相同SchoolName的记录组中使用窗口函数(而不是初始查询中的全局分区),然后,外部查询按SchoolName进行过滤和聚合。
在**your DB Fiddlde**中,该函数返回:

| SchoolName | median_val |
| ---------- | ---------- |
| A          | 71         |
| B          | 254        |
| C          | 344        |
| D          | 233.5      |

相关问题