>>declare @t table (Id_number int, show_date date, attendance int) >>insert into @t (Id_number, show_date, attendance) >>values >>(1, '12/01/2016', 4000), >>(1, '03/04/2016', 3000), >>(1, '01/05/2016', 9500), >>(2, '03/01/2016', 2000), >>(2, '02/04/2016', 4000), >>(2, '01/01/2016', 5000), >>(2, '12/18/2015', 1000) >> >>;with cte as (select *, COALESCE(lag(show_date) over (partition by Id_number order by show_date), show_date) as PreviousDate, >>SUM(Attendance) over (partition by ID_number order by show_date) as RunningTotal >>from @t) >> >>select *, datediff(day, PreviousDate, show_date) as [Days Passed] from cte >>Do you want to find the very first date when attendance was greater than 5000 and check the difference with it or find the first record when attendance was greater than 5000 but the previous date was more than 90 days?
declare @t table (Id_number int, show_date date, attendance int) insert into @t (Id_number, show_date, attendance) values (1, '12/01/2016', 4000), (1, '03/04/2016', 3000), (1, '01/05/2016', 9500), (2, '03/01/2016', 2000), (2, '02/04/2016', 4000), (2, '01/01/2016', 5000), (2, '12/18/2015', 1000) ;with cte as (select *, COALESCE(lag(show_date) over (partition by Id_number order by show_date), show_date) as PreviousDate from @t), cte2 as (select *, datediff(day, PreviousDate, show_date) as [Days Passed], row_number() over (partition by Id_number order by show_date) as Rn from cte where attendance > 5000) select * from cte2 where Rn = 1 and [Days Passed] > 90For the latter case it will be
select top (1)* from cte where [Days Passed] > 90 and Attendance > 5000 order by show_date-- no need for cte2