The objective is to accept the first complaint received and reject all the complaints received in the 1 hour following the first complaint. For example I have the data below.
| ComplaintID | DateTime |
|---|---|
| 1 | 12/24/2019 1:07 PM |
| 2 | 12/24/2019 1:20 PM |
| 3 | 12/24/2019 1:40 PM |
| 4 | 12/24/2019 2:00 PM |
| 5 | 12/24/2019 2:10 PM |
| 6 | 12/24/2019 2:12 PM |
| 7 | 12/24/2019 2:50 PM |
| 8 | 12/24/2019 2:55 PM |
| 9 | 12/24/2019 3:00 PM |
| 10 | 12/24/2019 3:08 PM |
| 11 | 12/24/2019 4:00 PM |
| 12 | 12/24/2019 4:50 PM |
| 13 | 12/24/2019 7:00 PM |
| 14 | 12/26/2019 7:01 PM |
Required Output:
| ComplaintID | DateTime | Status |
|---|---|---|
| 1 | 12/24/2019 1:07 PM | Accept |
| 2 | 12/24/2019 1:20 PM | Reject |
| 3 | 12/24/2019 1:40 PM | Reject |
| 4 | 12/24/2019 2:00 PM | Reject |
| 5 | 12/24/2019 2:10 PM | Accept |
| 6 | 12/24/2019 2:12 PM | Reject |
| 7 | 12/24/2019 2:50 PM | Reject |
| 8 | 12/24/2019 2:55 PM | Reject |
| 9 | 12/24/2019 3:00 PM | Reject |
| 10 | 12/24/2019 3:08 PM | Reject |
| 11 | 12/24/2019 4:00 PM | Accept |
| 12 | 12/24/2019 4:50 PM | Reject |
| 13 | 12/24/2019 7:00 PM | Accept |
| 14 | 12/26/2019 7:01 PM | Accept |
I understand that this would be easy using a programming language, however I need a solution in SQL.
EDIT:
Based on @Gordon's suggestion, I implemented the following recursive query and it works! However, it seems inefficient on large data.
with RECURSIVE t AS (
select row_number as rn,ts, lag(ts,1) over (order by row_number) as baseline from main_table where row_number<3
UNION ALL
SELECT
rn+1 as rn
,(select ts from main_table where row_number=rn+1) as ts
,case when datediff('hour',ts,baseline)>24 then ts else baseline end as baseline
from (select * FROM t order by rn desc limit 1 )t where rn<=(select count(*)-1 from main_table)
)
,real_baseline as
(
select rn,ts,lead(baseline,1) over (order by rn) as real_baseline from t
)
select *
,case when row_number() over (partition by real_baseline order by ts) =1 then 'Accept'
else 'Reject' end as status
from real_baseline