2014-05-14 79 views
0

在一個表中我有超過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 
+0

你能在[ID]添加索引和[SDateTime]列 –

+0

指數很好地工作已經添加,但仍需要時間。 – Sami

回答

0

嘗試這樣做!

select * from 
(
SELECT ID, Lat, Long, SDateTime, 
row_number() OVER (partition BY [ID] ORDER BY [SDateTime] DESC) AS rowNum 
FROM  
dbo.myTable WITH (NOLOCK) 
)x 
where x.rowNum=1 
+0

你能簡單解釋一下你的答案嗎? –

0

這應該做的工作,但它會與一個索引(ID,SDateTime)

;with d as (
    select distinct id 
    from myTable 
) 
select 
    mt.* 
from d 
cross apply (
    select top 1 * 
    from myTable m 
    on m.id = d.id 
    order by [SDateTime] DESC 
) mt