Я не хочу здесь красть гром Гордона, потому что он выполнил сложную часть.
Вот дополнительные бит , конвертирующие NULL в «Первый раз».
create table #pivottabledata(Rownum int, PersonId int, Month int);
insert into #pivottabledata values(1,123,1);
insert into #pivottabledata values(2,123,2);
insert into #pivottabledata values(3,123,4);
insert into #pivottabledata values(4,123,5);
insert into #pivottabledata values(5,123,12);
insert into #pivottabledata values(1,222,1);
insert into #pivottabledata values(2,222,3);
insert into #pivottabledata values(3,222,4);
select * from #pivottabledata;
with cte (rownum,personid,month,diff) AS
(
select rownum, personid, month,
(month -
lag(month) over (partition by personid order by month)
) as diff
from #pivottabledata
)
SELECT rownum personid, month,
ISNULL(CAST(diff AS VARCHAR(max)), 'First Time') as diff
from cte;