1

SQLServer2000の使用

表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 に答える