我有一个BorderCrossingData表。 A希望获取PassportNames至少有一个BorderCrossingDateTime-interval,该间隔超过4个月。
BorderCrossingID PassportNumber BorderCrossingDateTime
1 ER-2222 2019-01-07 22:11:12.000
2 ER-2222 2019-01-07 23:11:12.000
3 KL-5233 2018-10-03 17:10:39.000
130 FF-4444 2019-01-08 11:11:11.000
5 ER-1111 NULL
6 KL-5686 NULL
7 ER-1111 NULL
8 KL-5235 NULL
9 QW-5656 NULL
10 DF-5685 NULL
11 KL-4558 NULL
--------
113 LL-8989 2019-01-15 16:24:26.333
114 ZZ-0005 2019-01-17 16:18:12.273
115 LL-0223 2019-01-17 16:19:12.000
116 ER-2222 2019-01-03 08:24:29.000
117 ER-2222 2019-02-01 08:25:03.873
118 ER-2222 2019-03-13 08:25:17.000
119 ER-2222 2019-04-10 08:25:32.000
120 ER-2222 2019-09-30 08:25:47.000
我已经获得BorderCrossings的BorderCrossingDateTime并将它们置于顺序中。
SELECT DISTINCT PassportNumber, BorderCrossingDateTime FROM Passports
WHERE DATEDIFF(Compare 2 upcoming DateTimes)
EXCEPT
SELECT PassportNumber, BorderCrossingDateTime FROM Passports
WHERE BorderCrossingDateTime IS NULL
ORDER BY BorderCrossingDateTime
结果应该是这样的:
PassportName
ER-2222
TO-0140
NN-4444
TP-0140
TT-0140
WU-5645
答案 0 :(得分:0)
下面的代码将起作用。我已经在SQL Server中进行了测试。我正在使用LEAD,LAG函数来查找上一个,下一个过境日期。
CREATE TABLE #borderCrossing (BorderCrossingID INT, PassportNumber VARCHAR(10), BorderCrossingDateTime DATETIME)
INSERT INTO #borderCrossing
VALUES (1, 'ER-2222', '2019-01-07 22:11:12.000'), (2, 'ER-2222', '2019-03-07 22:11:12.000'), (3, 'ER-2222', '2019-08-07 22:11:12.000');
SELECT DISTINCT PassportNumber
FROM (
SELECT BorderCrossingId, BorderCrossingDateTime AS CurrentBorderCrossingDateTime, passportNumber, lag(BorderCrossingDateTime, 1, NULL) OVER (
PARTITION BY passportNumber ORDER BY BorderCrossingDateTime
) AS prevBorderCrossingDateTime, lead(BorderCrossingDateTime, 1, NULL) OVER (
PARTITION BY passportNumber ORDER BY BorderCrossingDateTime
) AS nextBorderCrossingDateTime
FROM #borderCrossing
) AS t
WHERE DATEDIFF(mm, prevBorderCrossingDateTime, nextBorderCrossingDateTime) > 4