如何检查上一行和下一行值

时间:2012-09-04 04:18:38

标签: sql sql-server sql-server-2000

使用SQL Server 2000

表1

id date value

001 23/03/2012 P
001 24/03/2012 A
001 25/03/2012 P
001 26/03/2012 P

....

我想按日期检查前一行和下一行的值,如果它是P,那么我想创建一个当前行P

预期产出

id date value

001 23/03/2012 P
001 24/03/2012 P 'Updated as per the condition
001 25/03/2012 P
001 26/03/2012 P
....

如何查询上述条件

需要查询帮助

2 个答案:

答案 0 :(得分:1)

查看下面的示例脚本。

DECLARE @Table TABLE(
        ID VARCHAR(20),
        [Date] DATETIME,
        Value VARCHAR(10)
)

INSERT INTO @Table SELECT '001','23/Mar/2012','P' 
INSERT INTO @Table SELECT '001','24/Mar/2012','A' 
INSERT INTO @Table SELECT '001','25/Mar/2012','P' 
INSERT INTO @Table SELECT '001','26/Mar/2012','P'

SELECT  *
FROM    @Table

UPDATE  @Table
SET     Value = 'P'
FROM    @Table t
WHERE   t.Value = 'A'
AND             
        (
            SELECT  TOP 1
                    Value
            FROM    @Table tBelow
            WHERE   t.ID = tBelow.ID
            AND     t.Date > tBelow.Date
            ORDER BY tBelow.Date DESC
        ) = 'P' --Previous
AND     (
            SELECT  TOP 1
                    Value
            FROM    @Table tBelow
            WHERE   t.ID = tBelow.ID
            AND     t.Date < tBelow.Date
            ORDER BY tBelow.Date
        ) = 'P' --Next

SELECT  *
FROM    @Table

答案 1 :(得分:0)

-- Input parameters
declare @cur_id char(3)
declare @cur_dt datetime
set @cur_id = '001'
set @cur_dt = '2012-03-25'

-- Search previous/next row
declare @prev_dt datetime
declare @next_dt datetime

select  @prev_dt = max(date)
from    YourTable
where   id = @cur_id
        and date < @cur_dt
        and value = 'A'

select  @next_dt = min(date)
from    YourTable
where   id = @cur_id
        and date > @cur_dt
        and value = 'A'

-- Update previous/next row if found
update  YourTable
set     value = 'P'
where   id = '001'
        and date in (@prev_dt, @next_dt)