2016-12-22 80 views
0

我想要做的是找到所有具有相同的object_id發生在彼此的秒鐘內但具有不同的client_ip地址的記錄。基於兩個條件找到所有記錄:時間和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,有沒有一種方法,我可以比較記錄找到在每個記錄的第二秒內確實發生的所有object_id,但具有不同的client_ip?

感謝,

+0

你可以滯後/超前這一個。通過action_occurred命令設置您的結果集,然後讓您的查詢查看以下行,看看如果datediff小於1000毫秒。會嘗試寫出查詢,但沒有提供一個簡單的方法來重現它的示例數據。 – dfundako

+0

謝謝@dfundako - 我會檢查出LAG/LEAD,但如果您想重現它,我還會添加一些示例數據。 – MISNole

回答

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 
+0

謝謝你 - 非常有幫助。 – MISNole