更新时间:2021-06-30 16:25:15
步骤:
rn
,以防 id
不按顺序排列.approv_rn
,由 EmailApproved
分区,以便我们知道第二次 EmailApproved = 1
的时间outer apply
来查找EmailApproved = 1
second
实例的行号where
子句中,过滤掉所有行号为 >=
的行,即在步骤 3 中找到的值.EmailApproved
记录可用,则 outer apply
将返回 null,在这种情况下返回所有可用的行.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 = 1
where
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;