在 MSSQL 中使用附加的 max() 条件从数据库中检索每个组中的最后一条记录
Retrieving last record in each group from database with additional max() condition in MSSQL
这是 Retrieving last record in each group from database - SQL Server 2005/2008
的后续问题
在答案中,提供了此示例以检索一组参数的最后记录(下面的示例检索计算机名中每个值的最后更新):
select t.*
from t
where t.lastupdate = (select max(t2.lastupdate)
from t t2
where t2.computername = t.computername
);
然而,在我的例子中,"lastupdate" 不是唯一的(一些更新是分批进行的并且具有相同的 lastupdate 值,如果 "computername" 的两个更新出现在同一批次中,您将得到"computername + lastupdate" 的非唯一输出)。
假设我还有字段 "rowId" 只是自动递增。缓解措施是在查询中包含 max('rowId') 字段的另一个标准。
注意:虽然该示例使用了特定于时间的名称 "lastupdate",但实际的选择标准可能与时间根本无关。
因此,我想问,什么是 性能最高的 查询,它根据 "group-defining parameter" 选择每个组中的最后一条记录(在这种情况下上面,"computername") 和最大 rowId?
如果没有唯一性,那么row_number()
更简单:
select t.*
from (select t.*,
row_number() over (partition by computername order by lastupdate, rowid desc) as seqnum
from t
) t
where seqnum = 1;
有了正确的索引,相关子查询通常会更快。但是,性能差异并不大。
这是 Retrieving last record in each group from database - SQL Server 2005/2008
的后续问题在答案中,提供了此示例以检索一组参数的最后记录(下面的示例检索计算机名中每个值的最后更新):
select t.*
from t
where t.lastupdate = (select max(t2.lastupdate)
from t t2
where t2.computername = t.computername
);
然而,在我的例子中,"lastupdate" 不是唯一的(一些更新是分批进行的并且具有相同的 lastupdate 值,如果 "computername" 的两个更新出现在同一批次中,您将得到"computername + lastupdate" 的非唯一输出)。 假设我还有字段 "rowId" 只是自动递增。缓解措施是在查询中包含 max('rowId') 字段的另一个标准。
注意:虽然该示例使用了特定于时间的名称 "lastupdate",但实际的选择标准可能与时间根本无关。
因此,我想问,什么是 性能最高的 查询,它根据 "group-defining parameter" 选择每个组中的最后一条记录(在这种情况下上面,"computername") 和最大 rowId?
如果没有唯一性,那么row_number()
更简单:
select t.*
from (select t.*,
row_number() over (partition by computername order by lastupdate, rowid desc) as seqnum
from t
) t
where seqnum = 1;
有了正确的索引,相关子查询通常会更快。但是,性能差异并不大。