SQL Server内部连接在同一个表上

时间:2018-01-27 09:15:11

标签: sql-server

我有一个查询,使用同一个表上的内部联接来获取给定DEVICEID的记录。请指导我如何获取设备ID集的记录而不是一个。

这是查询:

SELECT 
    X.DeviceId, Y.RecordedTime, X.RecordedTime,
    (DATEDIFF(SECOND, Y.RecordedTime, X.RecordedTime)) SECONDS
FROM 
    (SELECT  
         ROW_NUMBER() OVER (ORDER RecordedTime DESC) SNO,
         [GCId],
         [DeviceId], [IgnitionStatus], [TruckNo],
         [TripId], [RecordedTime], [UploadTime], [SyncTime], EventCode
     FROM 
         [KYTE].[dbo].[KT_savetest1] 
     WHERE 
         DeviceId = '861693034654582' 
         AND (RecordedTime > '2018-01-22 00:00:05' AND
              RecordedTime < '2018-01-22 00:23:55')
         AND EventCode IN (1, 101)) X
INNER JOIN 
    (SELECT
         ROW_NUMBER() OVER (ORDER BY RecordedTime DESC) SNO,
         [GCId], [DeviceId], [IgnitionStatus], [TruckNo],
         [TripId], [RecordedTime], [UploadTime], [SyncTime], EventCode 
     FROM 
         [KYTE].[dbo].[KT_savetest1] 
     WHERE
         DeviceId = '861693034654582' 
         AND (RecordedTime > '2018-01-22 00:00:05' AND
              RecordedTime < '2018-01-22 00:23:59') 
         AND EventCode IN (1, 101)) Y ON X.SNO = Y.SNO - 1 
WHERE
    (DATEDIFF(SECOND, Y.RecordedTime, X.RecordedTime)) > 60

结果

86169303883567  2018-01-21 23:40:52   2018-01-21 23:41:53   61  1
86169303883567  2018-01-21 23:27:55   2018-01-21 23:28:56   61  1
86169303883567  2018-01-21 23:02:01   2018-01-21 23:03:02   61  1
86169303883567  2018-01-21 22:49:04   2018-01-21 22:50:05   61  1

0 个答案:

没有答案