在一個表中我有超過70萬分的記錄。當我運行此查詢時,需要3分鐘以上的時間才能獲取行,並根據rowNum返回390條記錄。有沒有辦法優化這個查詢?如何優化查詢,添加ROWNUMBER在where子句
SELECT ID, Lat, Long, SDateTime,
row_number() OVER (partition BY [ID] ORDER BY [SDateTime] DESC) AS rowNum
into #temp
FROM
dbo.myTable WITH (NOLOCK)
select * from #temp where rowNum = 1 -- returns 390 records
drop table #temp
我可以在一個查詢中選擇數據而不必將其放入臨時表嗎?像這樣:
SELECT ID, Lat, Long, SDateTime,
row_number() OVER (partition BY [ID] ORDER BY [SDateTime] DESC) AS rowNum
FROM
dbo.myTable WITH (NOLOCK)
where (row_number() OVER (partition BY [ID] ORDER BY [SDateTime] DESC)) = 1
你能在[ID]添加索引和[SDateTime]列 –
指數很好地工作已經添加,但仍需要時間。 – Sami