简体   繁体   English

SQL Server查询以查找间隔为12个月或更长时间的记录

[英]SQL Server query to find records with gap or 12 months or greater

I have a table of records, each record has a created date and a userid. 我有一个记录表,每个记录都有一个创建日期和一个用户名。

I am trying to find all records where there has been a gap of 12 months or greater between records for that given user. 我正在尝试查找该给定用户的记录之间有12个月或更长时间的间隔的所有记录。 Which is the most simplest method to do this I am writing this is in SQL Server? 我正在SQL Server中写这是最简单的方法?

select * 
from records 
where last record and lastest record is greater than 12 months.

You are looking for the lag() or lead() function. 您正在寻找lag()lead()函数。 This is available in SQL Server 2012+. 这在SQL Server 2012+中可用。

select r.*
from (select r.*,
             lag(createddate) over (partition by userid order by createddate) as last_createddate
      from records r
     ) r
where last_createddate is null or
      last_createddate < dateadd(year, -1, createddate);

In earlier versions of SQL Server, you can emulate the logic using outer apply , although the performance is often worse. 在早期版本的SQL Server中,您可以使用outer apply Apply来模拟逻辑,尽管性能通常会更差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM