Top n records per group sql in access

前端 未结 2 480
耶瑟儿~
耶瑟儿~ 2020-11-28 15:20

I am making some software that tracks the scores of a test. There are multiple users, the details of which are stored in a user table. There is then a progress table which t

相关标签:
2条回答
  • 2020-11-28 16:08

    I had a similar problem a year ago: Top 3 per group including 0

    Using the same approach, this will return the latest three dates for each LoginID - you may get more than three records if there are tied dates for the same LoginID.

    SELECT  PR1.LogInID, PR1.Score, PR1.[Date Taken]
    FROM    Progress AS PR1
    WHERE   PR1.[Date Taken] IN (
                            SELECT TOP 3 PR2.[Date Taken]
                            FROM    Progress PR2
                            WHERE   PR2.LoginID = PR1.LoginID
                            ORDER BY PR2.[Date Taken] DESC
                            )
    ORDER BY    LoginID, [Date Taken]
    
    0 讨论(0)
  • 2020-11-28 16:21

    I used the above code and it worked perfectly fine. But I really want the 3 rows irrespective of the score, so I tried to add another ranking for example Math score. If the Score is same 3 times, it must select one with max math score. I used the code as shown below but it returns the same results. Can you please help me rectify the mistake.

      SELECT  PR1.LogInID, PR1.Score, PR1.[Date Taken]
      FROM    Progress AS PR1
      WHERE   PR1.[Date Taken] IN (
              SELECT TOP 3 PR2.[Date Taken]
              FROM    Progress PR2
              WHERE   PR2.LoginID = PR1.LoginID AND PR2.Math_Score IN(
                        SELECT TOP 1 PR3.Math_Score
                        FROM    Progress PR3
                        WHERE   PR3.[Date Taken] = PR2.[Date Taken] 
                        ORDER BY PR3.Math_Score DESC)
                        
              ORDER BY PR2.[Date Taken] DESC
                        )
    ORDER BY    LoginID, [Date Taken], Math_Score
    
    0 讨论(0)
提交回复
热议问题