Search code examples
t-sqlsql-server-2014

Find All Records Based on Two Conditions: Time and IP


What I am trying to do is to find all records that have the same object_id that occurred within a second of each other but have different client_ip addresses.

Below are a few examples that I have found manually but I would like to be able to identify all records in the table for a particular date.

SELECT sa.client_ip, sa.action_occured, sa.[object_id]
--INTO #TmpB
FROM dbo.system_audit AS [sa]
WHERE sa.action_id = 9111 AND sa.object_type_id = 9100
AND sa.[object_id] IN (50017197, 50050471, 50100927,50145858,50144558);

And the results:

IP and Action Occurred

Sample data might help more than a screen shot:

client_ip                     action_occured           object_id
fe80::7996:b7de:c335:699b%12  2016-12-19 15:54:17.300  50017197
fe80::e41f:6383:5d0d:7b3%3    2016-12-19 15:54:17.410  50017197
fe80::e41f:6383:5d0d:7b3%3    2016-12-19 14:54:45.383  50050471
fe80::2117:63d8:2b67:91ab%12  2016-12-19 14:54:46.303  50050471
fe80::7996:b7de:c335:699b%12  2016-12-19 15:40:42.467  50100927
fe80::e41f:6383:5d0d:7b3%3    2016-12-19 15:40:42.763  50100927
fe80::7996:b7de:c335:699b%12  2016-12-19 14:12:54.147  50144558
fe80::118c:f37b:336d:c1c0%12  2016-12-19 14:12:54.270  50144558
fe80::b0de:8ce7:be87:582d%12  2016-12-19 14:20:30.770  50145858
fe80::149b:f256:e64c:4d59%12  2016-12-19 14:20:31.380  50145858

Without knowing the specific object_id, is there a way I could compare the records to find all object_id's that did occur within a second of each record but have different client_ip's?

Thanks,


Solution

  • As suggested by dfundako, here's a way you could do it with LAG/LEAD (and a CTE for clarity):

    WITH augmentedData (client_ip, action_occurred, [object_id], prev_date, prev_ip, next_date, next_ip)
    AS
    (
        SELECT  *, 
                LAG(action_occurred, 1)  OVER (PARTITION BY [object_id] ORDER BY action_occurred) AS prev_date,
                LAG(client_ip, 1)        OVER (PARTITION BY [object_id] ORDER BY action_occurred) AS prev_ip,
                LEAD(action_occurred, 1) OVER (PARTITION BY [object_id] ORDER BY action_occurred) AS next_date,
                LEAD(client_ip, 1)       OVER (PARTITION BY [object_id] ORDER BY action_occurred) AS next_ip
        FROM system_audit
    )
    
    SELECT  client_ip,
            action_occurred,
            [object_id]
    FROM augmentedData 
    WHERE (DATEDIFF(MS,prev_date,action_occurred) < 1000 AND prev_ip <> client_ip)
       OR (DATEDIFF(MS,action_occurred,next_date) < 1000 AND next_ip <> client_ip)
    ORDER BY action_occurred