我需要一个选择查询,返回2乘2分组的行对,条件是这些行的日期值必须是连续的。它的返回结果是这样的。
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个日期之间的差异超过1,查询也应该返回成对的行,可能是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]
Table1 t1
CROSS APPLY
SELECT top 1 percent
[Date],
Table1
WHERE
t1.[Date] < [Date]
ORDER BY [Date]
谢谢每一个试图帮助我的人。
2 个回答
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代替,case when NextRow.EFF_DATE is null then '20991231' else NextRow.EFF_DATE end with NextRow.EFF_DATE and left join with inner join。
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