Forum Moderators: open
SELECT SUM(Score) AS ScoreTotal ,AttendeeID,EventID FROM <TableName> GROUP BY AttendeeID,EventID ORDER BY ScoreTotal
What I now need is to produce a leader board based on the top 6 scores each attendee has. Rather than all of the scores they have.
Any suggestions.
The source data looks like this
EventID; AttendeeID; Score
1; John; 10
1; Jim; 9
1; Jo; 25
2; John; 20
2; Jo; 10
2; Jim; 9
so when I run the query
I get
ScoreTotal; AttendeeID;
35; JO
30; John
18; Jim
This is fine for now but once they get more than six results I only want there top 6 Results to be part of the SUM.
I have the following that may work, however this assumes a couple of things:
1. That you are storing AttendeeID as a Foreign Key, and storing AttendeeDetails in a different table.
2. That there will not be duplicate Scores in the table (which will probably invalidate this solution!)
It also uses two queries.
Q1.:
SELECT tblAttendees.AttendeeName, tblAttendeeScores.Score
FROM tblAttendees INNER JOIN tblAttendeeScores ON tblAttendees.AttendeeID = tblAttendeeScores.AttendeeID
WHERE (((tblAttendeeScores.Score) In (Select Top 6 [Score] From tblAttendeeScores Where [AttendeeID]=[tblAttendees].[AttendeeID] Order By [Score] Desc)))
ORDER BY tblAttendees.AttendeeName, tblAttendeeScores.Score DESC;
We then use this query (named Query 1 Below), to produce the second query, grouping the Attendee and Summing their Top 6 scores.
Q2.:
SELECT Query1.AttendeeName, Sum(Query1.Score) AS SumOfScore
FROM Query1
GROUP BY Query1.AttendeeName;
As stated, this only works correctly if the 6 scores are ALL different for each Attendee.
To get around this, you would probably need to do some kind of ranking per Attendee.
SELECT SUM(Score) AS ScoreTotal, AttendeeID, EventID
FROM <TableName> tab1
WHERE <primarykey> IN (SELECT TOP 6 <primarykey>
FROM <TableName> tab2
WHERE tab1.AttendeeID = tab2.AttendeeID
AND tab1.EventID = tab2.EventID
ORDER BY Score)
GROUP BY AttendeeID,EventID
ORDER BY ScoreTotal