如何在SQL Server中有效地获取上一行和下一行的值

时间:2013-02-19 07:05:57

标签: sql sql-server sql-server-2008 tsql

说我有这些行,

InstrumentID

547
698
708

InstrumentID不是自动生成的列。

如果我将过程中的参数传递为698,我应该将之前的值设为547,将下一个值设置为708.如何在SQL中有效地执行此操作?

我有这个程序,但效率不高(而且不正确)。

Alter PROCEDURE GetNextAndPreviousInsturmentID
(
    @InstrumentID   varchar(14),
    @PreviousInstrumentID   varchar(14) OUT,
    @NextInstrumentID   varchar(14) OUT
)
AS
BEGIN
    Declare @RowNum int = 0

    Select @RowNum = ROW_NUMBER() Over (Order by Cast(@InstrumentID as decimal(18))) From Documents Where InstrumentID = @InstrumentID 

    ;With normal As
    (   
        Select ROW_NUMBER() Over (Order by Cast(@InstrumentID as decimal(18))) as RowNum, Cast(InstrumentID as decimal(18)) as InstrumentID
            From Documents 
    )
    Select @PreviousInstrumentID = InstrumentID From normal
        Where RowNum = @RowNum - 1
    Select @NextInstrumentID = InstrumentID From normal
        Where RowNum = @RowNum + 1

END
GO

5 个答案:

答案 0 :(得分:10)

这是一个更简单的解决方案,但效率更高

SELECT P.PreviousID, N.NextID
FROM
(SELECT  MAX(D.InstrumentID) PreviousID
FROM Documents D
WHERE InstrumentID < @InstrumentID) P
CROSS JOIN
(SELECT  MIN(D.InstrumentID) NextID
FROM Documents D
WHERE InstrumentID > @InstrumentID) N

答案 1 :(得分:2)

试试这个:

Alter PROCEDURE GetNextAndPreviousInsturmentID
(
    @InstrumentID   varchar(14),
    @PreviousInstrumentID   varchar(14) OUT,
    @NextInstrumentID   varchar(14) OUT
)
AS
BEGIN

    Declare @Ids TABLE(Id varchar(14))

    ;With normal As
    (   
        --Numerate our rows
        Select ROW_NUMBER() Over (Order by Cast(Documents.InstrumentID as decimal(18)) as RowNumber,
               Documents.InstrumentID
        From Documents 

    )
    --Insert three rows from our table with our id and previos/next id
    INSERT INTO @Ids(Id)
    SELECT TOP(3) normal.InstrumentID
    FROM normal
    WHERE RowNumber >=
        (
            SELECT RowNumber - 1
            FROM normal
            WHERE normal.InstrumentID = @InstrumentID
        )
    ORDER BY normal.RowNumber
    --select next and previos ids

    SELECT @PreviousInstrumentID = Min(CAST(Id as decimal(18))),
           @NextInstrumentID = MAX(CAST(Id as decimal(18)))
    FROM @Ids
END
GO

在MS SQL 2012中,我们有新的窗口函数,如FIRST_VALUE和LAST_VALUE,遗憾的是在sql 2008中缺少这些函数。

答案 2 :(得分:0)

WITH CTE AS (
  SELECT rownum = ROW_NUMBER() OVER (ORDER BY p.LogDate), p.LogDate
  FROM DeviceLogs p
)
SELECT prev.logdate PreviousValue, CTE.logdate, nex.logdate NextValue
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1

GO

答案 3 :(得分:-1)

嗨,我认为这会更有效率:

选择下一步:

select top 1 ID from mytable
where ID >'698'
order by ID asc

选择上一个:

select top 1 ID from mytable
where ID <'698'
order by ID desc

答案 4 :(得分:-1)

选择

LAG(InstrumentID) OVER (ORDER BY InstrumentID) PreviousValue,
InstrumentID, 
LEAD(InstrumentID) OVER (ORDER BY InstrumentID) NextValue
from documents