sql - Select two consecutive records by date, records from the database, with a maximum difference of dates -


i want select 2 consecutive records date, records database, maximum difference in consecutive dates.

there table

 name date abc  1242 bcd  1246 bsd  1247 bse  1249 

the result of query should be:

 abc  1242 bcd  1246 

my query is:

     select t1.name, t2.name, max(t2.date - t1.date)     temp t1     join temp t2 on t1.date < t2.date         not exists (         select t3.date temp t3 t3.date > t1.date , t3.date < t2.date     ) 

is best solution?

thanks in advance

declare @a table(name varchar(10), date int) insert @a select 'abc',  1242 union select 'bcd',  1246 union select 'bsd',  1280 union select 'bse',  1242  select row_number() on (order name) 'rownumber',*  #temp @a  select top 1 * #tbl ( select a1.name n1,a2.name n2,abs(a2.date-a1.date) diff  #temp a1 join #temp a2 on a2.rownumber-1  = a1.rownumber  )as tbl order diff desc  select * @a name =(select n1 #tbl) or name =(select n2 #tbl)  drop table #temp drop table #tbl 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -