簡體   English   中英

在MSSQL中使用額外的max()條件從數據庫中檢索每個組中的最后一條記錄

[英]Retrieving last record in each group from database with additional max() condition in MSSQL

這是從數據庫中檢索每個組中的最后一條記錄的后續問題- 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”,但實際選擇標准可能與時間無關。

因此,我想問一下,根據“組定義參數”(在上面的情況下,“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;

使用正確的索引,相關子查詢通常更快。 但是,性能差異並不是那么大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM