Hi @Scott Graham ,
Welcome to Microsoft Q&A!
For this type of problem we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.
Please also refer below whether it is helpful:
create table Remediation
(
LoanName varchar(10),
CustomerName varchar(20),
Startdate date,
Enddate date
)
insert into Remediation values
('Loan1','Cust1','2011-03-01','2013-04-01'),
('Loan1','Cust2','2012-04-01','2015-04-01'),
('Loan1','Cust3','2018-09-01',NULL)
;with cte as (
select *,LEAD(Startdate) over (partition by LoanName order by Startdate) as ned
from Remediation
),cte1 as (
select LoanName,CustomerName,Startdate ,case when Enddate>ned then ned else Enddate end Enddate
from cte)
,cte2 as (
select LoanName,Startdate,Enddate
from cte1
union all
select t.LoanName,cte2.Startdate, t.Enddate
from cte2
join cte1 t on cte2.Enddate = t.Startdate and cte2.LoanName=t.LoanName
)
, cte3 as (
select *, rn = row_number() over (partition by LoanName,Enddate order by Startdate)
from cte2
)
select LoanName,min(Startdate) Startdate, max(Enddate) Enddate
from cte3
where rn=1
group by LoanName,Startdate
Output:
LoanName Startdate Enddate
Loan1 2011-03-01 2015-04-01
Loan1 2018-09-01 NULL
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.