1

使用 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
....

如何查询上述条件

需要查询帮助

4

2 回答 2

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
于 2012-09-04T04:27:55.460 回答
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)
于 2012-09-04T04:25:30.073 回答