T-SQL 多行之间的日期差异

T-SQL date difference between multiple rows

我想要 Id_Pass 两个或多个日期之间相差超过 10 天的情况。我试过 datediff 但我觉得它变得太复杂了。

+------------+-----------+-------+
|    Date    |  Id_Pass  | Value |
+------------+-----------+-------+
| 2011-03-18 | PASS00004 |    30 |
| 2011-03-19 | PASS00004 |    60 |
| 2012-02-25 | PASS00005 |    30 |
| 2012-04-25 | PASS00005 |    30 |
+------------+-----------+-------+

想要的结果:

+-----------+
|  Id_Pass  |
+-----------+
| PASS00005 |
+-----------+

您可以使用 lag() 函数

select * from
(
select *, DATEDIFF(day, LAG(Date,1, Date) OVER (partition by Id_Pass ORDER BY Date)) as daydiff
)A where daydiff>10

只需使用 LAG window 函数查找每一行的上一个日期:

SELECT Id_Pass
FROM (
    SELECT Id_Pass, Date, LAG(Date) OVER (PARTITION BY Id_Pass ORDER BY Date) AS PrevDate
    FROM yourdata
) AS cte
WHERE Date > DATEADD(DAY, 10, PrevDate)