我有下表:
+------------+-------+
| 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) );
要计算整个“分数”列的平均值,但我不知道如何分别针对每所学校。
请帮忙吗?
答案 0 :(得分:1)
您的查询使用用户变量来计算行号,这使得处理分区更加复杂。由于您使用的是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 |