2011-01-11 252 views
4

我們有一所有38所小學的學區。孩子們接受了考試。學校的平均分佈很廣,但我想比較每所學校只有十名學生的平均水平。獲得每所學校前10名學生的平均分

要求:僅使用臨時表。

我已經完成了這個工作非常密集,容易出錯,如下所示。
(sch_code =例如,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 - 看起來像家庭作業,但這是...,真的。

回答

8

使用this technique

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 
+0

+1。只有變量名稱與我的解決方案不同:) – Ronnis 2011-01-11 19:28:32