I have the following query where I am trying to select all records, ordered by date, until the second time EmailApproved = 1 is found. The second record where <
Steps:
rn, over all rows in case id is not in sequence.approv_rn, partitioned by EmailApproved so we know when EmailApproved = 1 for the second timeouter apply to find the row number of the second instance of EmailApproved = 1where clause filter out all rows where the row number is >= the value found in step 3.EmailApproved records available then the outer apply will return null, in which case return all available rows. ; with test as
(
select *,
rn = row_number() over (order by Created desc),
approv_rn = row_number() over (partition by EmailApproved
order by Created desc)
from @Test
)
select *
from test t
outer apply
(
select x.rn
from test x
where x.EmailApproved = 1
and x.approv_rn = 2
) x
where t.rn < x.rn or x.rn is null
order by t.Created desc