SQL Server:只有 GROUP BY 中的最后一个条目

2021-12-27 00:00:00 sql group-by sql-server

我在 MSSQL2005 中有下表

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

现在我想根据 business_key 进行分组,返回具有最高 ID 的完整条目.所以我的预期结果是:

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.

推荐答案

另一种解决方案,它可能会给您带来更好的性能(测试两种​​方式并检查执行计划):

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

这个查询假设 ID 是一个唯一值(至少对于任何给定的 business_key)并且它被设置为 NOT 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.

相关文章