SQL Server: Only last entry in GROUP BY

group-by, sql, sql-server

Solution

An alternative solution, which may give you better performance (test both ways and check the execution plans):

SELECT
     T1.id,
     T1.business_key,
     T1.result
FROM
     dbo.My_Table T1
LEFT OUTER JOIN dbo.My_Table T2 ON
     T2.business_key = T1.business_key AND
     T2.id > T1.id
WHERE
     T2.id IS NULL

This query assumes that the ID is a unique value (at least for any given business_key) and that it is set to NOT NULL.

Problem

I have the following table in MSSQL2005 ``` id | business_key | result 1 | 1 | 0 2 | 1 | 1 3 | 2 | 1 4 | 3 | 1 5 | 4 | 1 6 | 4 | 0 ``` And now i want to group based on the business_key returning the complete entry with the highest id. So my expected result is: ``` business_key | result 1 | 1 2 | 1 3 | 1 4 | 0 ``` I bet that there is a way to achieve that, i just can't see it at the moment.

Original source