;with cte_1 as (
select a.*
from mytable a
inner join (select ID,srno from mytable b
where srno >= (select max(srno) from mytable c
where b.ID = c.ID and date1 < @start_date )
and (case when date1 < @start_date and status = 'start' then 'start' end )= 'start'
) b on a.ID = b.ID
where not exists(select ID from mytable b where a.ID = b.ID
and (status = 'end' or date1>@end_date)) and
b.srno = a.srno - 1),
cte_2 as (
select
a.*
from mytable a
inner join (
select ID , max(srno) srno from mytable f where exists(select ID from mytable e
where status = 'start' and f.ID = e.ID and e.date1 >= @start_date
and e.date1 < dateadd(d,1,@end_date))
group by ID
) b on a.ID = b.ID )
select * from cte_1 union
select * from cte_2 c2 where not exists (select 1 from cte_1 c1 where c1.id = c2.id)
|