I have a small table that looks like this:
PLAN YRMTH
A2BKG 197001
A2BKG 200205
A2BKG 200308
A2BKG 200806
From this table, how do I get a table such as the one below?
PLAN STARTDATE ENDDATE
A2BKG 197001 200205
A2BKG 200205 200308
A2BKG 200308 200806
A2BKG 200806 NULL
Try this
;with cte as
(select *, ROW_NUMBER() over (partition by [plan] order by yrmth) rn from yourtable)
select
t1.[plan],
t1.YRMTH as startdate,
t2.YRMTH as enddate
from cte t1
left join cte t2 on t1.[plan]=t2.[plan]
and t1.rn=t2.rn-1