I have the following table variable in SQL Server 2005:
DECLARE @results TABLE (id int IDENTITY(1,1),
customerId int,
salesId int,
score int,
lastServiceDate datetime,
PRIMARY KEY(id));
I need an efficient way to clean the table or access the table's results, so that it returns only 1 result per salesId. If there is more than 1 result per salesId, it should show the row with the highest score, or in the case of a tie, the most recent lastServiceDate from the Customer table.
Right now, my test data looks like this:
id customerId salesId score lastServiceDate
1 950 418 3 2009-08-09 00:00:00.000
2 951 418 3 2009-08-19 00:00:00.000
3 952 418 1 2009-08-22 00:00:00.000
4 953 419 2 2009-08-15 00:00:00.000
I want something that would return, in this instance, just two rows--id 2 (top score/lastServiceDate for salesId 418) and id 4 (only result for salesId 419). In the end, I need to take the data in this table, and insert it into a JobResult table, selecting customerId, and salesId from @results, with these restrictions.
(This finishes a question asked in http://stackoverflow.com/questions/1343647.)