Этого можно достичь с помощью оконной функции для ранжирования посещений, которые начинаются в тот же день, что и конец initial
, а затем пару простых join
s:
declare @t table(ID int,color varchar(20),begin_date date,end_date date,location varchar(20));
insert into @t values(1,'red','20170101','20170107','initial'),(1,'green','20170105','20170107','nursing'),(1,'blue','20170107','20170115','rehab'),(1,'red','20170111','20170122','Health'),(2,'red','20170222','20170226','initial'),(2,'green','20170226','20170228','nursing'),(2,'blue','20170226','20170228','rehab'),(3,'red','20170311','20170322','initial'),(4,'red','20170401','20170407','initial'),(4,'green','20170405','20170407','nursing'),(4,'blue','20170410','20170415','Health');
with d as
(
select ID
,color
,begin_date
,end_date
,location
,row_number() over (partition by ID
,begin_date
order by case when location = 'initial' then '29990101' else begin_date end
) as r
from @t
)
select i.ID
,isnull(d.location,isnull(h.location,'Home')) as first_site
from d as i
left join d
on i.end_date = d.begin_date
and d.r = 1
left join d as h
on i.ID = h.ID
and h.location = 'Health'
where i.location = 'initial'
;
Выход:
+----+------------+
| ID | first_site |
+----+------------+
| 1 | rehab |
| 2 | nursing |
| 3 | Home |
| 4 | Health |
+----+------------+