删除与上次24小时内收到的同名记录

时间:2017-11-01 10:56:29

标签: sql sql-server

我正在使用此代码

DECLARE @ThisMonth DATETIME;
SET @ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), 
'19000101');

select
id,
received,
siteid,
loggedbyteam,
closedbyteam,

from 
tbl.OpenAndClosed

where
received >= DATEADD(MONTH, -1, @ThisMonth)
and received <  @ThisMonth

在这张桌子上

Id  Received                  closed                    siteid          
1   2017-10-09 08:01:00.000   2017-10-09 16:00:00.000   500 
2   2017-10-09 08:01:00.000   2017-10-09 13:00:00.000   212 
3   2017-10-09 08:02:00.000   2017-10-09 08:07:30.540   499 
4   2017-10-09 08:10:00.000   2017-10-09 08:10:17.510   454 
5   2017-10-09 08:12:00.000   2017-10-09 08:15:12.297   454 
6   2017-10-09 08:35:00.000   2017-10-09 08:35:41.127   454 
7   2017-10-09 08:38:00.000   2017-10-09 14:50:00.000   696 
8   2017-10-09 08:38:00.000   2017-10-09 15:15:00.000   212 
9   2017-10-12 08:39:00.000   2017-10-12 15:41:37.527   454     
10  2017-10-09 08:49:00.000   2017-10-10 09:23:39.283   455 

哪个可以正常

但我想要做的是排除具有相同记录的记录 siteid,并在最后一条记录关闭后的24小时内收到。

这是我正在寻找的结果。

Id  Received                 closed                     siteid   
1   2017-10-09 08:01:00.000  2017-10-09 16:00:00.000    500 
2   2017-10-09 08:01:00.000  2017-10-09 13:00:00.000    212 
3   2017-10-09 08:02:00.000  2017-10-09 08:07:30.540    499 
5   2017-10-09 08:12:00.000  2017-10-09 08:15:12.297    454     
7   2017-10-09 08:38:00.000  2017-10-09 14:50:00.000    696 
8   2017-10-11 08:38:00.000  2017-10-11 15:15:00.000    212 
9   2017-10-12 08:39:00.000  2017-10-12 15:41:37.527    454 
10  2017-10-09 08:49:00.000  2017-10-10 09:23:39.283    455 

ID4和ID5将从结果中删除,因为它在关闭后24小时内打开了新记录。

ID8和ID9仍然存在是因为它们在24小时开放之前没有关闭记录。

Essentually, &#34;排除任何具有相同siteid且已关闭且已收到24小时的记录。&#34;

如果您需要更多信息,请告诉我。

2 个答案:

答案 0 :(得分:1)

我认为以下内容可以满足您的需求:

select t.*
from (select id, received, closed, siteid, loggedbyteam, closedbyteam,
             lag(closed) over (partition by siteid order by closed) as prev_closed
      from tbl.OpenAndClosed oac
      where received >= DATEADD(MONTH, -1, @ThisMonth) and
            received <  @ThisMonth
     ) oac
where prev_closed < dateadd(day, -1, closed) or prev_closed is null;

答案 1 :(得分:0)

第一步是确定哪些行具有重复值:

SELECT colname1, colname2, count(*)
FROM table
GROUP BY colname1, colname2
HAVING count(*) > 1

然后使用此查询进行删除:

set rowcount 1
delete from table
where colname1=1 and colname2=1 and date = currentdate