简体   繁体   中英

SQL Server previous and next date from a million row table

I'm trying to write an efficient query for selecting previous date and next date from a million row table in SQL Server 2008. Below is my query. I've created a non clustered index on batchdetailid and with include fields on tranId, EquipmentID and Date. I have yet to finish the query since it takes hours. Any help would be much appreciated. Also below is the output getting.

Previous Date              Date                   Next Date
--------------------------------------------------------------------------------
1/12/2015 06:09:34|1/12    1/12/2015 07:10:59      1/13/2015 03:30:04


 WITH CTE AS (
    SELECT
    rownum = ROW_NUMBER() OVER (ORDER BY TransactionID),
    p.TransactionID,
    p.DateTime,
    EquipmentID
    FROM table p
    where BatchDetailID = 11225 
    )
SELECT
CTE.EquipmentID,
CTE.TransactionID,
CTE.DateTime,
nex.TransactionID NextValue,
nex.DateTime NextDateTime,
prev.TransactionID PreviousValue,
prev.EventDateTime PreviousDate
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1

Sqlserver will usually mess up the join when using CTE. This is likely to perform faster:

SELECT 
  rownum = ROW_NUMBER() OVER (ORDER BY TransactionID), 
  p.TransactionID, p.DateTime, EquipmentID 
INTO #t
FROM yourtable p 
WHERE BatchDetailID = 11225

SELECT
  t.EquipmentID,
  t.TransactionID,
  t.DateTime,
  nex.TransactionID NextValue,
  nex.DateTime NextDateTime,
  prev.TransactionID PreviousValue,
  prev.EventDateTime PreviousDate
FROM #t t
LEFT JOIN #t prev ON prev.rownum = t.rownum - 1
LEFT JOIN #t nex ON nex.rownum = t.rownum + 1

DROP table #t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM