访问总和前5名为组

时间:2017-04-04 10:59:09

标签: sql ms-access

我有一个Access表,我想在其中总结每组的前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

我希望有人可以帮助我,因为我无法找到正确的查询

2 个答案:

答案 0 :(得分:0)

using (Image image = Image.FromStream(new MemoryStream(ReceiveVarData(clientSock))))
{
    if (image != null)
        pictureBox1.Image = image;
}

答案 1 :(得分: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;

问题是MS Access中的TOP确实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;