SQL Server: Only last entry in GROUP BY

后端 未结 5 1077
日久生厌
日久生厌 2020-12-10 16:15

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 wa

5条回答
  •  天涯浪人
    2020-12-10 16:40

    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.

提交回复
热议问题