0

我目前拥有的数据类似于下面的表格:

 UserId      VisitDate
 1           2012-01-01 00:15:00.000
 1           2012-01-01 00:16:00.000
 1           2012-01-12 00:15:00.000
 1           2012-01-12 00:16:00.000
 1           2012-01-24 00:15:00.000
 1           2012-01-24 00:16:00.000

我想只返回相隔 10 天或更长时间的结果,看起来像这样:

 UserId      VisitDate
 1           2012-01-01 00:15:00.000
 1           2012-01-12 00:15:00.000
 1           2012-01-24 00:15:00.000

也许比我做的更简单,但是如何在 transact-sql 中这样做呢?

4

1 回答 1

1

在这种情况下,您可以使用新lag()功能:http: //msdn.microsoft.com/en-us/library/hh231256.aspx

就像是:

SELECT UserId, VisitDate
FROM(
  SELECT UserId,
         VisitDate, 
         LAG(VisitDate,1,'1900-01-01')OVER(PARTITION BY UserId ORDER BY VisitDate) PrevVisitDate
   FROM dbo.YourTable
)X
WHERE DATEDIFF(day,PrevVisitDate,VisitDate)>=10;

你可以在这里看到它的作用:http ://sqlfiddle.com/#!6/a0f02/1

于 2013-02-13T17:12:32.710 回答