SQL Server:只有GROUP BY中的最后一项 [英] SQL Server: Only last entry in GROUP BY

查看:72
本文介绍了SQL Server:只有GROUP BY中的最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  id |在MSSQL2005中有以下表格

business_key |结果
1 | 1 | 0
2 | 1 | 1
3 | 2 | 1
4 | 3 | 1
5 | 4 | 1
6 | 4 | 0

现在我想根据business_key返回具有最高id的完整条目。
所以我的预期结果是:

  business_key |结果
1 | 1
2 | 1
3 | 1
4 | 0

我敢打赌,有一种方法可以实现这一点,我只是无法在。

解决方案

另一种解决方案可以提供更好的性能(测试两种​​方式并检查执行计划) p>

  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。


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.

解决方案

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.

这篇关于SQL Server:只有GROUP BY中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆