2017-04-04 45 views
0

我有一個訪問表,其中我想總結每個組的前5名結果。 表例如:訪問總額前5組

Club Points Score 
    c1 25  200 
    c1 20 150 
    c1 15 100 
    c1 25 200 
    c1 25 200 
    c1 25 200 
    c2 25 200 
    c2 20 150 
    c2 15 100 

期望的結果將是:

Club Points Score 
c1  120  950 
c2  60  450 

我希望有人能幫助我,因爲我無法找到這個

回答

0
select SUM(Points),SUM(Score) FROM table_name GROUP BY Club 
0

正確的查詢要正確地做到這一點,你真的需要每行有一個唯一的ID。其基本思想是:

select club, sum(points), sum(score), count(*) as nummatches 
from t 
where score in (select top 5 t2.score 
       from t as t2 
       where t2.club = t.club 
       order by t2.score desc 
       ) 
group by club; 

的問題是,TOP在MS Access確實TOP WITH TIES。所以,如果有關係,你可以得到五個以上的值。這就是爲什麼查詢包含匹配數量的原因。

爲了解決這個問題,你可以這樣做:

select club, sum(points), sum(score), count(*) as nummatches 
from t 
where score in (select top 5 t2.score 
       from t as t2 
       where t2.club = t.club 
       order by t2.score desc, id -- the `id` makes each row unique 
       ) 
group by club; 
+0

看來,這是更成問題。我試過你的解決方案,但收到一個錯誤,它找不到t.club。問題是表t是從交叉表查詢創建的查詢。所以我不得不爲這個新查詢添加參數t.club = short text和id = integer。但現在當我開始查詢時,它要求我輸入t.club值和id值。任何想法如何解決這個問題? – Jonvejn

+0

't.club'是對外部查詢的引用。這絕對是MS Access支持的。 –