我目前正在寻找一个特定的数据条目,该条目是在特定的其他条目之前的第 3 个条目。我的主要问题是该表没有 id
字段,只有一个 date
字段。否则我就能找到一个好的解决方案。
例子: 该表包含以下字段:LogDate、LogEntry。
我期待以下数据:
2015-01-01 07:10:10 This is the 1st line I want
2015-01-01 07:11:10 Nothing to report
2015-01-01 07:11:13 Nothing to report
2015-01-01 07:15:10 Tag
2015-01-01 07:17:10 Nothing to report
2015-01-01 07:20:10 Nothing to report
2015-01-01 07:30:10 Nothing to report
2015-01-01 07:32:10 This is the 2nd line I want
2015-01-01 07:35:10 Nothing to report
2015-01-01 07:40:10 Nothing to report
2015-01-01 07:41:10 Tag
2015-01-01 07:43:10 Nothing to report
2015-01-01 07:44:10 Nothing to report
2015-01-01 07:45:10 Nothing to report
2015-01-01 07:54:10 Nothing to report
2015-01-01 07:55:10 This is the 3rd.....
.....
预期的结果是:
This is the 1st line I want
This is the 2nd line I want
我用来获取标记行的 sql 是:
SELECT LogEntry
From myTable
where LogEntry = 'Tag' and LogDate >= '2015-01-01 05:00:00'
order by LogDate ASC
这让我得到了“标签”条目。我不确定的是,是否有可能在不使用游标/存储过程或 C# 程序或...的情况下获取每个上方第 3 行的条目。
注意:SQL Server 版本为 2012
最佳答案
使用 LEAD
查看以下记录。
select logdate, logentry
from
(
select logdate, logentry, lead(logentry, 3) over (order by logdate) as logentry3
from mytable
) t
where logentry3 = 'Tag';
关于sql - 是否可以在不依赖游标和 ID 的情况下找到特定条目前 3 个条目的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238079/