SQL如何选择日期连续的行对?

时间:2014-08-08 08:50:52

标签: sql sql-server sql-server-2008

我有以下简单的表格:

create table Table1(
ID int NOT NULL IDENTITY(1,1),
[Date] datetime
)

我需要一个select查询,返回2对2的行对,条件是行的Date值必须是连续的。返回的内容如下:

1   2014-08-10 09:29:53.160 2   2014-08-11 09:29:53.160
2   2014-08-11 09:29:53.160 3   2014-08-12 09:29:53.160
3   2014-08-12 09:29:53.160 4   2014-08-13 09:29:53.160
4   2014-08-13 09:29:53.160 5   2014-08-14 09:29:53.160

我做了这个查询:

select * from Table1 t1
inner join Table1 t2 on t1.ID < t2.ID
where t2.Date = DATEADD(DD,1,t1.Date)

但问题是查询应返回行对,即使两个日期之间的差异大于一,它可能是2,3,10,x ...... 另外我被告知t1.ID < t2.ID验证不合适,我应该像这样威胁案例:

2   2014-08-09 09:29:53.160
1   2014-08-10 09:29:53.160 

使用大量插入的行时,查询也应该很快。

我的意思是,如果我有以下输入:

1   2014-08-09 09:29:53.160 
2   2014-08-11 09:29:53.160 
3   2014-08-12 09:29:53.160 
4   2014-08-14 09:29:53.160 
5   2014-08-18 09:29:53.160 

然后输出应该是:

1 2014-08-09 09:29:53.160 2 2014-08-11 09:29:53.160 
2 2014-08-11 09:29:53.160 3 2014-08-12 09:29:53.160 
3 2014-08-12 09:29:53.160 4 2014-08-14 09:29:53.160
4 2014-08-14 09:29:53.160 5 2014-08-18 09:29:53.160

有人给了我正确答案,但我看到他删除了答案。它是:

SELECT 
  t1.id, 
  t1.[Date],
  x.id,
  x.[Date]
FROM
  Table1 t1
CROSS APPLY
(
  SELECT top 1 percent 
    [Date],
    ID
  FROM 
    Table1
  WHERE 
    t1.[Date] < [Date]
  ORDER BY [Date]
) x

感谢所有试图帮助我的人。

2 个答案:

答案 0 :(得分:0)

试试这个:

select id
,Current_Row.EFF_DATE
,case when NextRow.EFF_DATE is null then '20991231' else NextRow.EFF_DATE end
from TABLE1 as Current_Row
left join TABLE1 as NextRow
on NextRow.iD = Current_Row.iD + 1

如果不需要为最后日期设置间隔,则可以替换,例如,当NextRow.EFF_DATE为空时,则为&#39; 20991231&#39; else NextRow.EFF_DATE以NextRow.EFF_DATE结束,并使用内连接

左连接

答案 1 :(得分:0)

试试这个:

SELECT t1.ID, t1.Date, t3.ID AS ID1, t3.Date AS Date1 
FROM Table1 AS t1
    OUTER APPLY 
        (SELECT TOP 1 t2.ID, t2.Date 
            FROM Table1 AS t2
            WHERE t2.Date <= t1.Date AND t2.ID < t1.ID
            ORDER BY t2.Date DESC, t2.ID DESC) AS t3

Example