本文介绍了SQL Server:只有 GROUP BY 中的最后一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我在 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.
这篇关于SQL Server:只有 GROUP BY 中的最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)