SQL Server: Only last entry in GROUP BY(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 中的最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server:只有 GROUP BY 中的最后一个条目
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
