按日期选择两个连续记录,数据库中的记录,最大日期差异

时间:2013-05-14 13:35:33

标签: sql sql-server odbc

我想按日期选择两个连续记录,数据库中的记录,连续日期的最大差异。

有一张表

name date
abc  1242
bcd  1246
bsd  1247
bse  1249

查询结果应为:

abc  1242
bcd  1246

我的查询是:

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

这是最好的解决方案吗?

提前致谢

2 个答案:

答案 0 :(得分:0)

declare @a table(name varchar(10), date int)
insert into @a Select 'abc',  1242
union Select 'bcd',  1246
union Select 'bsd',  1280
union Select 'bse',  1242

Select row_number() OVER (ORDER BY name) AS 'RowNumber',*  into #temp from @a

select Top 1 * into #tbl from
(
select a1.Name as N1,a2.Name as N2,abs(a2.date-a1.date) as diff
 from #temp a1 Join #temp a2 on a2.rownumber-1  = a1.rownumber
 )as tbl order by diff desc

select * from @a where name =(select N1 from #tbl) or name =(select N2 from #tbl)

Drop table #temp
Drop table #tbl

答案 1 :(得分:0)

我的解决方案,至少对SQL 2012有用!

declare @data table (name varchar(10), date int)

-- Your test data
insert into @data (name, date) values ('abc', 1242),('bcd',  1246),('bsd',  1247),('bse',  1249)

SELECT d.name, d.date FROM (
  SELECT TOP 1 name, prevName FROM (
    SELECT name, prevName, date-prevDate as datePrevDiff FROM (
      SELECT name, date
        , MAX(d.name) OVER (ORDER BY d.date ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) as prevName
        , MAX(d.date) OVER (ORDER BY d.date ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) as prevDate
      FROM @data d
    ) dataWithPrev
  ) dataWithPrevDiff
  ORDER BY datePrevDiff DESC
) largestDiff
INNER JOIN @data d ON d.name in (largestDiff.name, largestDiff.prevName)

这假设按日期排序是正确的做法......