1

I want to select all records in a table except some records which are repeated for a CustId in given time interval.

Following is the simple example to understand requirement, Lets say I want to skip records repeating within 60 Mins (60 Mins is time interval) for same CustId. As you can see in below data, row Id 2 and 3 repeated for 'Cust1' and row Id 6 repeated for 'Cust2'.

+-----------------------------------+
| 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' |
+----+---------+--------------------+

So the result should be

+-----------------------------------+
| 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' |
+----+---------+--------------------+

Any help is appreciated.

Shri
  • 351
  • 3
  • 16

2 Answers2

2

Join the table to itself and use built-in function 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
Ali Azam
  • 2,047
  • 1
  • 16
  • 25
1

You can do it like this where you use LAG to compare times

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

Result

enter image description here

SqlKindaGuy
  • 3,501
  • 2
  • 12
  • 29