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 中的最后一个条目
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
