我需要删除表中的所有记录,其间的时间介于1或2分钟之间或相同且必须相同ID
但保留第一条记录
ID Time SN SD WE FW
10 2014-06-30 19:17:37.000 I 0 100 0
10 2014-06-30 19:17:42.000 I 0 100 0
10 2014-06-30 19:17:46.000 I 0 100 0
10 2014-06-30 19:17:58.000 I 0 100 0
10 2014-06-30 20:37:46.000 I 0 100 0
或
ID Time SN SD WE FW
10 2014-07-01 21:10:33.000 I 0 100 0
10 2014-07-01 21:11:06.000 O 0 100 0
10 2014-07-02 20:53:36.000 I 0 100 0
10 2014-07-02 20:53:38.000 I 0 100 0
10 2014-07-02 20:54:33.000 O 0 100 0
10 2014-07-02 20:54:41.000 O 0 100 0
10 2014-07-02 20:55:22.000 o 0 100 0
是
ID Time SN SD WE FW
10 2014-06-30 19:17:37.000 I 0 100 0
10 2014-06-30 20:37:46.000 I 0 100 0
和
ID Time SN SD WE FW
10 2014-07-01 21:10:33.000 I 0 100 0
10 2014-07-02 20:53:36.000 I 0 100 0
ITS无法正常工作 抱歉,我是新的@sql这个MY Table内容
SELECT TOP 1000
[USERID]
,[CHECKTIME]
,[CHECKTYPE]
,[VERIFYCODE]
,[SENSORID]
,[WorkCode]
,[sn]
FROM
[NEWFP].[dbo].[CHECKINOUT]
我需要删除时间为2或1分钟的记录并保留第一个但用户ID相同的记录。
我不能这样做?
答案 0 :(得分:1)
你走了!
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
答案 1 :(得分:0)
对于您的特定表格,请尝试以下代码。它假设USERID是&#34; ID&#34;从你原来的问题和CHECKTIME是&#34;时间&#34;。希望这对你有用!
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