简体   繁体   中英

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. Which is the most simplest method to do this I am writing this is in 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. This is available in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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