我在SQL Server 2016数据库中具有下表:
Time Identifier Category
1. 2821-01-04 17:41.0 1002 A1001
2. 2821-01-05 17:41.0 1002 A1001
3. 2821-01-06 17:42.0 1001 A1001
4. 2821-01-07 17:44.0 1002 A1001
5. 2821-01-08 17:44.0 1002 A1001
6. 2821-01-09 17:44.0 1002 A1001
7. 2821-01-10 17:44.0 1002 A1001
8. 2821-01-11 17:44.0 1002 A1001
9. 2821-01-12 17:44.0 1002 A1001
10. 2821-01-13 17:44.0 1002 A1001
11. 2821-01-14 17:45.0 1001 A1001
12. 2821-01-15 17:46.0 1002 A1001
13. 2821-01-16 17:46.0 1002 A1001
14. 2821-01-17 17:46.0 1002 A1001
15. 2821-01-18 17:46.0 1002 A1001
16. 2821-01-19 17:46.0 1002 A1001
17. 2821-01-20 17:46.0 1002 B1001
18. 2821-01-21 17:46.0 1002 B1001
19. 2821-01-22 17:46.0 1002 B1001
20. 2821-01-23 17:46.0 1001 B1001
21. 2821-01-24 17:48.0 1002 B1001
22. 2821-01-25 17:48.0 1002 B1001
23. 2821-01-26 17:48.0 1002 B1001
24. 2821-01-27 17:48.0 1002 B1001
25. 2821-01-28 17:48.0 1001 B1001
26. 2821-01-29 17:52.0 1002 B1001
27. 2821-01-30 17:52.0 1002 B1001
28. 2821-01-31 17:52.0 1002 B1001
29. 2821-02-01 17:52.0 1002 B1001
我需要的是一个SQL查询,该查询获取任意2个连续行之间的时间差,对于每个[Category],第一个是[Identifier] = 1001,第二个是[Identifier] = 1002(也就是说,仅应针对同一类别进行计算)。 要考虑的连续记录对为:记录[3,4]和[11,12]和[20,21]和[25,26]。首先将[identifier]设为1001,将连续的[identifier]设为1002,将其视为一对。 因此,我们首先需要识别这些对。仅在同一[Category]中的对是相关的。属于不同类别的对应该被忽略。
我需要知道这些对之间的差异是1秒,2秒,2秒...最多5秒。
所需的输出:
Num of seconds Category Count
1 A1001 1
2 A1001 1
3 A1001 0
4 A1001 0
5 A1001 0
1 B1001 0
2 B1001 1
3 B1001 0
4 B1001 1
5 B1001 0
答案 0 :(得分:0)
我相信以下内容将带您进入球场。
SELECT *
FROM
(
SELECT
[time],
[identifier],
[category],
CASE WHEN identifier = 1001 THEN DATEDIFF(SECOND, [time], LEAD([time]) OVER (PARTITION BY Category ORDER BY [time], identifier)) END as TimeDiff
FROM yourtable
)timesub
WHERE identifier = 1001
ORDER BY category, TimeDiff