Optimizing ROW_NUMBER() in SQL Server

Posted by BlueRaja on Stack Overflow See other posts from Stack Overflow or by BlueRaja
Published on 2010-06-02T17:42:42Z Indexed on 2010/06/02 17:43 UTC
Read the original article Hit count: 329

We have a number of machines which record data into a database at sporadic intervals. For each record, I'd like to obtain the time period between this recording and the previous recording.

I can do this using ROW_NUMBER as follows:

WITH TempTable AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Machine_ID ORDER BY Date_Time) AS Ordering
    FROM dbo.DataTable
)

SELECT [Current].*, Previous.Date_Time AS PreviousDateTime
FROM TempTable AS [Current]
INNER JOIN TempTable AS Previous 
    ON [Current].Machine_ID = Previous.Machine_ID
    AND Previous.Ordering = [Current].Ordering + 1

The problem is, it goes really slow (several minutes on a table with about 10k entries) - I tried creating separate indicies on Machine_ID and Date_Time, and a single joined-index, but nothing helps.

Is there anyway to rewrite this query to go faster?

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about sql-server-2005