Quantcast
Channel: dBforums – Everything on Databases, Design, Developers and Administrators
Viewing all articles
Browse latest Browse all 13329

Select Top Query and Order by Unique Field

$
0
0
Dear all,

I have a query (qrySource) that pulls the following information from my database.

ID: Autonumber
PlayerID: Numeric
TestID: Text
Score: Numeric

There are 6 tests and it is possible to score between 3 and 8 on each of the tests. Players can take the tests as many times as they like and their score is recorded in the database on each occasion.

A sample of the data for one player in two tests (AR and EC) is shown below ...

Code:

9197        615        AR        5
9210        615        AR        5
9193        615        AR        4
9273        615        EC        5
9269        615        EC        4
9271        615        EC        4
9270        615        EC        4
9208        615        EC        4
9266        615        EC        3

I then have a second query that should return the top two scores from each player in each test. The SQL for that query is posted below.

Code:

SELECT qrySource.ID, qrySource.PlayerID, qrySource.TestID, qrySource.Score
FROM qrySource INNER JOIN tblTests ON qrySource.TestID = tblTests.TestID
WHERE (((qrySource.Score) In (Select Top 2 [Score] From qrySource Where [TestID]=[tblTest].[TestID] Order By [Score] Desc, [ID])))
ORDER BY qrySource.TestID, qrySource.Score DESC;

I cannot get this query to distinguish between duplicate scores and it returns all values despite me trying to Order By ID which is a unique value. The above query returns ...

Code:

9210        615        AR        5
9197        615        AR        5
9273        615        EC        5
9271        615        EC        4
9270        615        EC        4
9269        615        EC        4
9208        615        EC        4

Instead of what I want it to return, which is ...

Code:

9210        615        AR        5
9197        615        AR        5
9273        615        EC        5
9271        615        EC        4

Am I doing something wrong? Is the SQL in the right order?

Many thanks in anticipation of your help,
Dave

Viewing all articles
Browse latest Browse all 13329

Trending Articles