如何检查上一行和下一行的值
Posted
技术标签:
【中文标题】如何检查上一行和下一行的值【英文标题】:How to check the previous and next row values 【发布时间】:2012-09-04 04:18:38 【问题描述】:使用 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
....
如何查询上述条件
需要查询帮助
【问题讨论】:
以前基于什么标准?按日期?还是按日期按 ID? @astander,按日期选择 【参考方案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
【讨论】:
感谢您的回复,而不是更新我想查看表格,如何进行选择查询而不是更新...【参考方案2】:-- 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)
【讨论】:
以上是关于如何检查上一行和下一行的值的主要内容,如果未能解决你的问题,请参考以下文章
PowerShell 如果下一行包含“此字符串”,则输出当前行和下 3 行,否则仅输出当前行
SparkSql 查询以从 cassandra 获取定义值的上一行和下一行