I often verify logs in SQLServer and my query usually looks like this (where Type = 0 means error):
SELECT *
FROM Logs
WHERE Type = 0
ORDER BY Timestamp
But most of the time, I’m not only interested by the error itself but also at what happened immediately before the error.
Is it possible, with SQLServer, to query n lines above/under (relative to the primary key) each line matching the WHERE clause of the query?
Ex. With my query I would only get lines 125 & 130. I would like [123, 124, 125] and [128, 129, 130].
PrimaryKey Timestamp Type Description
123 2012-09-17 03:41:46.240 1 Working.
124 2012-09-17 03:42:46.240 1 Database backup.
125 2012-09-17 03:43:46.240 0 Access violation.
126 2012-09-17 03:44:46.240 1 Working.
127 2012-09-17 03:45:46.240 1 Working.
128 2012-09-17 03:46:46.240 1 Working.
129 2012-09-17 03:47:46.240 1 Backup.
130 2012-09-17 03:48:46.240 0 Corrupted.
131 2012-09-17 03:49:46.240 1 Working.
Thank you.
I would do it as follows:
The results would be as follows:
You can modify the join conditions using the relational operators to retrieve
nlines above and below the matching line.If the PrimaryKey column is not guaranteed to be sequential, then assuming that the records are always ordered by
TimestampinASCorder, the following query will fetch the before and after records to a selected one: