这是我的表记录
field_date field_time field_id
20161202 12:56:00 309073
20161202 12:57:00 208901
20161202 12:58:00 208901
20161202 13:15:00 208901
具有相同的ID(208901)我想删除时间间隔低于15分钟的ID,例如那里,这是我想要的结果
field_date field_time field_id
20161202 12:56:00 309073
20161202 12:57:00 208901
20161202 13:15:00 208901
id与12:58:00时间被删除,因为它与id第一条记录只有1分钟的间隔,但13:15:00没有被删除,因为间隔距离第一条记录超过15分钟。
这是我的代码,它仍然显示12:58:00记录,我想删除它所以我只会显示间隔少于15分钟的记录,此代码只显示所有记录(不是我想要的重复记录,那里有什么问题?
SELECT *
FROM tbl_name WHERE EXISTS (SELECT 1 FROM tbl_name t2
WHERE(t2.field_id = tbl_name.field_id AND
DATEDIFF(MINUTE, t2.field_time, tbl_name.field_time) <= 15)
)
ORDER BY field_time
答案 0 :(得分:1)
这个(对于SQL Server 2012 +):
DECLARE @DataSource TABLE
(
[field_date] INT
,[field_time] VARCHAR(8)
,[field_id] INT
);
INSERT INTO @DataSource ([field_date], [field_time], [field_id])
VALUES (20161202, '12:56:00', 309073 )
,(20161202, '12:57:00', 208901)
,(20161202, '12:58:00', 208901)
,(20161202, '13:15:00', 208901);
WITH DataSource ([field_date], [field_time], [field_id], [timeDiff]) AS
(
SELECT *
,DATEDIFF(MINUTE, MIN([field_time]) OVER(PARTITION BY [field_date], [field_id] ORDER BY [field_time] ASC), [field_time])
FROM @DataSource
)
SELECT *
FROM DataSource
WHERE [timeDiff] = 0
OR [timeDiff] > 15
ORDER BY field_time;
答案 1 :(得分:0)
DECLARE @Data TABLE ([field_date] int, [field_time] varchar(8), [field_id] int);
INSERT INTO @Data
VALUES
(20161202, '12:56:00', 309073),
(20161202, '12:57:00', 208901),
(20161202, '12:58:00', 208901),
(20161202, '13:15:00', 208901)
;
;WITH data AS
(
SELECT
*,
-- A field easier to use for comparison, e.g. cross date
CONVERT(datetime, CAST(field_date AS char(8)), 112) + CONVERT(time, field_time) AS combined_time
FROM @Data
)
DELETE curr
FROM
data curr
OUTER APPLY
(
SELECT TOP 1 *
FROM data prev
WHERE
prev.field_id = curr.field_id
-- assume the record does not contain duplicate record of field_time
AND prev.combined_time < curr.combined_time
ORDER BY combined_time DESC
) AS prev
WHERE DATEDIFF(MINUTE, prev.combined_time, curr.combined_time) <= 15
-- Result
SELECT * FROM @Data
答案 2 :(得分:0)
尝试如下:
0xff