我需要找到分数从null变为非null的客户端(例如1,4,7)。我使用外部申请获得最近的分数,这是空的。我的SQL在下面,它不对。你能帮我解决一下吗?谢谢!
SELECT DISTINCT
CLT_NBR,
t.SCORE
FROM TABLE_CLIENT t
OUTER APPLY
( SELECT TOP 1 t2.SCORE
FROM TABLE_CLIENT t2
WHERE t2.CLT_NBR= t.CLT_NBR AND t2.START_DT<t.START_DT
ORDER BY t2.START_DT DESC
) AS sprev
WHERE t.SCORE IS NOT NULL
AND sprev.SCORE IS NULL
答案 0 :(得分:2)
使用exists()
:(如果以前的得分为null
,则返回行)
select distinct
clt_nbr
, score
from table_client t
where score is not null
and exists (
select 1
from table_client i
where i.clt_nbr = t.clt_nbr
and i.start_dt < t.start_dt
and i.score is null
)
使用cross apply()
:(而不是outer apply()
,因此我们不会获得没有上一行的行)
select
t.clt_nbr
, t.score
from table_client t
cross apply (
select top 1 i.score
from table_client i
where i.clt_nbr = t.clt_nbr
and i.start_dt < t.start_dt
order by i.start_dt desc
) as x
where t.score is not null
and x.score is null
使用lag()
(SQL Server 2012+):(返回最近一次得分为null
的行)
with cte as (
select
clt_nbr
, score
, start_dt
, prev_score = lag(score) over (partition by clt_nbr order by start_dt)
, prev_start_dt = lag(score) over (partition by clt_nbr order by start_dt)
from table_client t
)
select
clt_nbr
, score
from cte
where score is not null
and prev_score is null
and prev_start_dt is not null