sql - 是否可以在不依赖游标和 ID 的情况下找到特定条目前 3 个条目的条目?

标签 sql sql-server sql-server-2012

我目前正在寻找一个特定的数据条目,该条目是在特定的其他条目之前的第 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/

相关文章:

javascript - 从数据库中获取嵌套 JSON 的最佳方法是什么?

sql - Rails 中的用户查询字符串

MySQL 更新查询不适用于不同的列

mysql - SQL在预订系统中查找连续两天

sql - 以所需格式格式化结果集时出现问题

sql-server - 如果文件存在,SQL Server 备份到 URL 将失败

sql-server-2012 - 此执行语句在 SQL Server 2012 中如何工作

mysql - 如何在 SQL Server 2012 中的单个查询中使用 alter table column 和 add constraint

sql - 如何传递变量内字符串的参数值?

sql - SQL Server 2012或2008中两行之间的时间差