SQL Server查询以选择除在特定时间间隔内重复的记录之外的所有记录

时间:2017-11-23 14:48:16

标签: sql-server sql-server-2012

我想选择表格中的所有记录,除了在给定时间间隔内为CustId重复的一些记录。

以下是理解要求的简单示例,假设我想跳过相同CustId在60分钟内重复的记录(60分钟是时间间隔)。 正如您在下面的数据中看到的那样,对于'Cust1'重复行Id 2和3,为'Cust2'重复行Id 6。

+-----------------------------------+
| Id | CustId  | CapturedTime       |
+-----------------------------------+
| 1  | 'Cust1' | '2017-10-01 10:30' |
| 2  | 'Cust1' | '2017-10-01 10:45' | -- Duplicate Row
| 3  | 'Cust1' | '2017-10-01 11:35' | -- Duplicate Row
| 4  | 'Cust1' | '2017-10-01 12:40' |
| 5  | 'Cust2' | '2017-10-01 16:15' |
| 6  | 'Cust2' | '2017-10-01 17:00' | -- Duplicate Row
| 7  | 'Cust4' | '2017-10-02 08:00' |
| 8  | 'Cust1' | '2017-10-02 10:45' |
| 9  | 'Cust3' | '2017-10-02 13:00' |
| 10 | 'Cust3' | '2017-10-02 14:05' |
+----+---------+--------------------+

所以结果应该是

+-----------------------------------+
| Id | CustId  | CapturedTime       |
+-----------------------------------+
| 1  | 'Cust1' | '2017-10-01 10:30' |
| 4  | 'Cust1' | '2017-10-01 12:40' |
| 5  | 'Cust2' | '2017-10-01 16:15' |
| 7  | 'Cust4' | '2017-10-02 08:00' |
| 8  | 'Cust1' | '2017-10-02 10:45' |
| 9  | 'Cust3' | '2017-10-02 13:00' |
| 10 | 'Cust3' | '2017-10-02 14:05' |
+----+---------+--------------------+

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

将表连接到自身并使用内置函数Lag

SELECT t1.Id, t1.CastId, t1.capturedtime from Customer t1 INNER JOIN 
(SELECT *,LAG(capturedtime,1,0) OVER(PARTITION BY CastId,CAST(capturedtime as date) ORDER BY CastId,capturedtime) as tempTime FROM Customer) t2
ON t1.Id = t2.Id AND DATEDIFF(MINUTE,tempTime, t1.capturedtime) >= 60

答案 1 :(得分:1)

您可以使用LAG来比较时间

declare @myt table (id int,custid nvarchar(50),capturedtime datetime
)

insert into @myt
values
( 1 , 'Cust1', '2017-10-01 10:30'),
( 2 , 'Cust1', '2017-10-01 10:45'),
( 3 , 'Cust1', '2017-10-01 11:35'),
( 4 , 'Cust1', '2017-10-01 12:40'),
( 5 , 'Cust2', '2017-10-01 16:15'),
( 6 , 'Cust2', '2017-10-01 17:00'),
( 7 , 'Cust4', '2017-10-02 08:00'),
( 8 , 'Cust1', '2017-10-02 10:45'),
( 9 , 'Cust3', '2017-10-02 13:00'),
( 10, 'Cust3', '2017-10-02 14:05')

select ID,Custid,CapturedTime from (
select * ,datediff(MINUTE,odtime,capturedtime) mm from (
select *,LAG(capturedtime,1,0) over(partition by custid,cast(capturedtime as date )order by custid,capturedtime) as odtime from @myt
)x
)z where mm >= 60
order by id

<强>结果

enter image description here