按组显示前两个求和值

Displaying the top two of summed values by group

我有一个名为 "QueryTotalGrades" 的查询,它包含三个字段(Group、StudentID 和 Mark)。每个 studentID 都有一个以上的分数。我想要做的是创建另一个执行以下操作的查询:

1- Sum mark for each studentID as a sumOfMark (Descending order)
2- Display the top 2 of sumOfMarks per group. 

示例:假设 "QueryTotalGrades" 具有以下值。 我使用的是 Microsoft Access 2013

Group    StudentID     Mark
1           1            8
1           1            7
1           1            8
1           2            7
1           2            7
1           2            7
1           3            9
1           3            9
1           3            9
2           4            5
2           4            7
2           4            5
2           5            7
2           5            7
2           5            7
2           6            6
2           6            6
2           6            6
3           7            8
3           7            7
3           7            8
3           8            7
3           8            7
3           8            7
3           9            10
3           9            10
3           9            10

,所以我想要的输出应该如下

Group    StudentID     SumOfMark
1           3            27
1           1            23
2           5            21
2           6            18    
3           9            30
3           7            23

我尝试了很多解决方案,但都无济于事。帮助

查询

;with cte as
(
   select rn=row_number() over
   (
       partition by [Group]
       order by sum(Mark) desc
   ),
  [Group],StudentID,
  sum(Mark) as SumOfMark
  from student
  group by [Group],StudentID
 )
 select [Group],StudentId,SumOfMark from cte where rn in (1,2);

fiddle demo

有点啰嗦但是:

select 
    t1.[Group], t1.StudentID, t1.SumOfMark
from

    (select [Group], StudentID, sum(Mark) as SumOfMark
    from QueryTotalGrades
    group by [Group], StudentID) as t1

where

    (select count(*) from

        (select [Group], StudentID, sum(Mark) as SumOfMark
        from QueryTotalGrades
        group by [Group], StudentID) as t2

        where 
            t2.[Group] = t1.[Group] and
            t2.SumOfMark >= t1.SumOfMark) <= 2

order by 
     t1.[Group], t1.SumOfMark desc

你可以在这里玩:SQL Fiddle