Это решение использует external apply для выборки предыдущей строки.
-- sample data
declare @mytable table
(
Model nvarchar(5),
StartingNo int,
EndingNo int
);
insert into @mytable (Model, StartingNo, EndingNo) values
('X', 1, 100),
('X', 150, 200),
('Y', 10, 30),
('Y', 1, 5);
-- solution
select t1.*,
t3.EndingNo as 'PreviousEndingNo',
t1.StartingNo - t3.EndingNo as 'Diff'
from @mytable t1
outer apply ( select top 1 t2.EndingNo -- first row...
from @mytable t2
where t2.Model = t1.Model -- ... with same model
and t2.StartingNo < t1.StartingNo -- ... that comes before current row
order by t2.StartingNo desc ) t3 -- ... when sorting on start number
order by t1.Model, t1.StartingNo;
Это дает:
Model StartingNo EndingNo PreviousEndingNo Diff
----- ----------- ----------- ---------------- -----------
X 1 100 NULL NULL
X 150 200 100 50
Y 1 5 NULL NULL
Y 10 30 5 5