[英]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. 我正在尝试编写一种有效的查询,以从SQL Server 2008中的一百万行表中选择上一个日期和下一个日期。以下是我的查询。 I've created a non clustered index on batchdetailid and with include fields on tranId, EquipmentID and Date. 我在batchdetailid上创建了一个非聚集索引,并在tranId,EquipmentID和Date上包含了include字段。 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. 使用CTE时,Sqlserver通常会弄乱连接。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.