问题描述
我有一个具有一百万条记录的表。这是表格的结构,其中包含一些示例数据点-
bullet
我需要编写一个查询来生成此输出-
patient claim thru_dt cd start
322 65 20200201 42 20181008
322 65 20200202 42
322 95 20200203 52
122 05 20200105 23
122 05 20200115 42 20190102
122 05 20200116 42
给予患者322的第二项索赔patient claim thru_dt cd start
322 65 20200201 42 20181008
322 65 20200202 42 20181008
322 95 20200203 52 20181008
122 05 20200105 23
122 05 20200115 42 20190102
122 05 20200416 42
的原因是,第一项和第二项都具有相同的20181008
值。
即使患者322的第三项索赔没有相同的cd
值,也为其赋予了20181008
值,这是因为这是该患者的最后一项索赔。
患者122的第一项索赔仍然为NULL的原因是,该索赔的cd
值不等于42。
即使患者122的第三项索赔具有相同的cd
值,也没有为其提供20190102
值,这是因为他们先前的索赔中的thru_dt相距超过30天。 / p>
这是我到目前为止尝试过的-
cd
解决方法
我认为横向联接和条件表达式使实现所需逻辑更简单:
select t.*,case
when t.start is null and (
s.cd = t.cd
or row_number() over(partition by t.patient order by t.thru_dt desc) = 1
)
then s.start
else t.start
end new_start
from mytable t
outer apply (
select top (1) s.*
from mytable s
where
s.patient = t.patient
and s.start is not null
and s.thru_dt >= dateadd(day,-30,t.thru_dt)
order by s.thru_dt desc
) s
order by patient desc,thru_dt
patient | claim | thru_dt | cd | start | new_start ------: | ----: | :--------- | -: | :--------- | :--------- 322 | 65 | 2020-02-01 | 42 | 2018-10-08 | 2018-10-08 322 | 65 | 2020-02-02 | 42 | null | 2018-10-08 322 | 95 | 2020-02-03 | 52 | null | 2018-10-08 122 | 5 | 2020-01-05 | 23 | null | null 122 | 5 | 2020-01-15 | 42 | 2019-01-02 | 2019-01-02 122 | 5 | 2020-04-16 | 42 | null | null