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

时间:2018-12-03 11:46:55

标签: sql-server database tsql datetime datediff

我希望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 |
+-----------+

2 个答案:

答案 0 :(得分:2)

只需使用LAG窗口函数为每一行查找上一个日期:

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)

答案 1 :(得分:0)

您可以使用lag()函数

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