I need to delete all records in a table where the time between it 1 or 2 minute or the same and must be the same ID
but keep the first record
ID
For your specific table, please try the code below. It assumes USERID is the "ID" from your original question and CHECKTIME is the "Time". Hope this works for you!
DECLARE @Seconds INT = 120
;WITH Logs AS (
SELECT
[USERID] AS ID,
[CHECKTIME] AS [Time],
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [Time]) AS RowNum
FROM [NEWFP].[dbo].[CHECKINOUT] L
)
DELETE L2
FROM Logs L1
INNER JOIN Logs L2
ON L1.ID = L2.ID
AND L1.RowNum = L2.RowNum - 1
WHERE DATEDIFF(SS, L1.[Time], L2.[Time]) < @Seconds
Here you go!
DECLARE @Seconds INT = 120
DECLARE @Logs TABLE (
ID INT,
[Time] DATETIME
)
INSERT @Logs VALUES
(10, '2014-06-30 19:17:37.000'),
(10, '2014-06-30 19:17:42.000'),
(10, '2014-06-30 19:17:46.000'),
(10, '2014-06-30 19:17:58.000'),
(10, '2014-06-30 20:37:46.000'),
(10, '2014-07-01 21:10:33.000'),
(10, '2014-07-01 21:11:06.000'),
(10, '2014-07-02 20:53:36.000'),
(10, '2014-07-02 20:53:38.000'),
(10, '2014-07-02 20:54:33.000'),
(10, '2014-07-02 20:54:41.000'),
(10, '2014-07-02 20:55:22.000')
;WITH Logs AS (
SELECT
ID,
[Time],
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY [Time]) AS RowNum
FROM @Logs L
)
--SELECT *, DATEDIFF(SS, L1.[Time], L2.[Time])
DELETE L2
FROM Logs L1
INNER JOIN Logs L2
ON L1.ID = L2.ID
AND L1.RowNum = L2.RowNum - 1
WHERE DATEDIFF(SS, L1.[Time], L2.[Time]) < @Seconds
SELECT * FROM @Logs