Mysql 获得每所学校前10名学生的平均成绩

Mysql 获得每所学校前10名学生的平均成绩,mysql,limit,temp-tables,Mysql,Limit,Temp Tables,我们有一个有38所小学的学区。孩子们进行了测试。学校的平均数分布很广,但我只想比较每所学校前10名学生的平均数 要求:仅使用临时表 我以一种工作密集、容易出错的方式完成了这项工作,如下所示。 sch_代码=例如,9043; -schabbrev=例如,卡特; -totpct_stu=例如,61.3 DROP TEMPORARY TABLE IF EXISTS avg_top10 ; CREATE TEMPORARY TABLE avg_top10 ( sch_code VARCHAR(

我们有一个有38所小学的学区。孩子们进行了测试。学校的平均数分布很广,但我只想比较每所学校前10名学生的平均数

要求:仅使用临时表

我以一种工作密集、容易出错的方式完成了这项工作,如下所示。 sch_代码=例如,9043; -schabbrev=例如,卡特; -totpct_stu=例如,61.3

DROP TEMPORARY TABLE IF EXISTS avg_top10 ;
CREATE TEMPORARY TABLE avg_top10
   ( sch_code   VARCHAR(4),
     schabbrev  VARCHAR(75),
     totpct_stu DECIMAL(5,1)
   );

INSERT 
  INTO avg_top10
SELECT sch_code
     , schabbrev
     , totpct_stu
  FROM test_table
 WHERE sch_code IN ('5489')
 ORDER
    BY totpct_stu DESC
 LIMIT 10;

-- I do that last query for EVERY school, so the total 
-- length of the code is well in excess of 300 lines.  
-- Then, finally...

SELECT schabbrev, ROUND( AVG( totpct_stu ), 1 ) AS top10
  FROM avg_top10
 GROUP
    BY schabbrev
 ORDER
    BY top10 ;

-- OUTPUT:
-----------------------------------
schabbrev   avg_top10
----------  ---------
Goulding         75.4
Garth            77.7
Sperhead         81.4
Oak_P            83.7
Spring           84.9
-- etc...
问:所以这是可行的,但是没有更好的方法吗

谢谢

PS-看起来像家庭作业,但这是,嗯…真实的。

使用


哇!当我看到代码是多么紧凑时,我的眼睛都瞪大了。从数百行到13行。是的,它像黄油一样有效。非常感谢你!!在MySQL 5.5.40中,这至少在连接其他表以测试_表时不起作用,因为ORDERBY发生在分配了行号之后。我必须从派生表中选择所有内容,并将其包装到另一个包含ORDERBY子句的派生表中,以使其正常工作。不过总体来说,这是一个很好的解决方案!
select sch_code,
       schabbrev,
       ROUND( AVG( totpct_stu ), 1 ) AS top10
from   (select sch_code,
               schabbrev,
               totpct_stu,
               @num := if(@group = sch_code, @num + 1, 1) as row_number,
               @group := sch_code as dummy
        from   test_table
        order by sch_code, totpct_stu desc) as x
where  row_number <= 10
GROUP BY sch_code,
       schabbrev