根据两个条件查找所有记录:时间和IP

时间:2016-12-22 15:03:05

标签: tsql sql-server-2014

我要做的是找到具有相同object_id的所有记录,这些记录彼此之间发生但具有不同的client_ip地址。

以下是我手动找到的一些示例,但我希望能够识别表格中特定日期的所有记录。

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);

结果:

IP and Action Occurred

示例数据可能比屏幕截图更有帮助:

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

在不知道具体的object_id的情况下,有没有办法比较记录,找到所有在每个记录的第二个内发生但又有不同client_ip的对象?

谢谢,

1 个答案:

答案 0 :(得分:1)

根据dfundako的建议,您可以使用LAG / LEAD(以及明确的CTE)来实现此目的:

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