Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

T-SQL Query for Top 1 for each date

Posted on 2012-03-13
2
Medium Priority
?
543 Views
Last Modified: 2012-08-13
Hello Experts,

I have a table called [Exam_Results], and it has to following colums:
[ID] int
[UserID] int
[ExamID] int
[Score] float
[Date] datetime

Users can take exams multiple times and the data looks as follows:

ID     UserID     ExamID     Score      Date
----------------------------------------------------------------------------
1          20            1               75          2012-02-15 13:30:00
2          20            1               83          2012-02-17 10:30:00
3          20            2               80          2012-02-15 13:30:00
4          54            3               64          2012-02-16 13:30:00
5          54            3               78          2012-02-20 14:30:00

What I am trying to get is the first time each user took the exam, so I want my select to return the top 1 result for each user.

So with the data above, my query would return:
UserID     ExamID     Score
-------------------------------------------
20                1              75
20                2              80
54                3              64

So, I need help to write a select query that for each User and Exam ID, will return the score from the first time the exam was completed by each user.
0
Comment
Question by:NursingCorp
2 Comments
 
LVL 8

Accepted Solution

by:
fundacionrts earned 2000 total points
ID: 37717576
SELECT ER1.UserID, ER1.ExamID, ER1.Score
FROM Exam_Results AS ER1
WHERE ER1.Date <= (
SELECT MIN( ER2.Date )
FROM Exam_Results AS ER2
WHERE ER2.UserID = ER1.UserID
AND ER2.ExamID = ER1.ExamID )
0
 

Author Closing Comment

by:NursingCorp
ID: 37717665
Worked Perfectly - Thanks for the clear, quick solution!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question