一尘不染

如何获取给定记录前后的记录?

sql

我具有以下表结构:

Id, Message
1, John Doe
2, Jane Smith
3, Error
4, Jane Smith

有没有办法获取错误记录和周围的记录?即找到所有错误以及它们之前和之后的记录。


阅读 124

收藏
2021-03-17

共1个答案

一尘不染

;WITH numberedlogtable AS
(
SELECT Id,Message, 
ROW_NUMBER() OVER (ORDER BY ID) AS RN
 FROM logtable
)

SELECT Id,Message
FROM numberedlogtable
WHERE RN IN (SELECT RN+i
             FROM numberedlogtable
             CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
             WHERE Message='Error')
2021-03-17