忽略小于X时间的结果

时间:2013-02-13 17:00:43

标签: tsql sql-server-2012

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

 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中这样做呢?

1 个答案:

答案 0 :(得分: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