SQL Server上一个和下一个日期来自一百万行表

时间:2016-03-09 09:44:21

标签: sql sql-server

我正在尝试编写一个有效的查询,用于从SQL Server 2008中的百万行表中选择上一个日期和下一个日期。以下是我的查询。我在batchdetailid上创建了一个非聚集索引,并在tranId,EquipmentID和Date上创建了包含字段。我还没有完成查询,因为它需要几个小时。任何帮助将非常感激。下面是输出结果。

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

1 个答案:

答案 0 :(得分:0)

使用CTE时,Sqlserver通常会搞乱连接。 这可能会更快地执行:

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