答案 0 :(得分:3)
我认为lag()
是您想要的:
select rownum, personid, month,
(month -
lag(month) over (partition by personid order by month)
) as diff
from t;
请注意,对于第一行,diff
将是NULL
,而不是'First Time'
。
您可以here对其进行测试。
答案 1 :(得分:1)
我不想在这里偷戈登的雷声,因为他做的很辛苦。
这是额外的bit,将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;