;with Data(ID)as( select 100 union all select 200 union all select 300 union all select 400 union all select 500)select *from Data douter apply( select top 1 ID from Data d2 where d2.ID < d.ID order by ID desc) x
--===== Create the test data. -- This is NOT a part of the solution. -- We're just building the test data table -- to look as expected. SELECT ID = Number INTO #YourTable FROM master.dbo.spt_values WHERE Type = 'P' AND Number %100 = 0;--===== Add the expected clustered index. -- This is also NOT a part of the solution. -- We're just building the test data table -- to look as expected. ALTER TABLE #YourTable ADD PRIMARY KEY CLUSTERED (ID);--===== This is the classic solution that will work on all versions of -- SQL Server and is very fast in the presence of the correct index. SELECT ID, MID = (SELECT TOP 1 ID FROM #YourTable t2 WHERE t2.ID < t1.ID ORDER BY t1.ID DESC) FROM #YourTable t1;
MID=(CASE WHEN ID-100=0 THEN NULL ELSE ID-100 END )