2

I am trying to think of a way of grouping some dates to make a count if they are more then 5 days apart.

For Example:

ID - DATE
22   15/05/2016 08:57
22   15/05/2016 10:50
22   15/05/2016 12:01
22   16/05/2016 01:12
22   22/05/2016 02:25

So for this I would currently get a count of 5 as there are 5 occurrences however I want to only get a count for 2 due to the fact that the first 4 have sequential dates and the final one is 5 days after the previous date so would need that counted as a new one.

Hopefully that makes sense!

1
  • 1
    Is the 5 day gap measured from the first day of a set or the last day? E.g. would 1,2,3,4,5,6,7,8,9 be one set (all consecutive) or two (1+5 = 6, 7+5 > 9)? What about 2,5,8,11,14,17,20,23,26? Commented Mar 6, 2017 at 11:52

1 Answer 1

2

If I understand your question, the following is the query that you are looking for.

SQL> select * from mytest;

        ID DT
---------- ---------
        22 15-MAY-17
        22 15-MAY-17
        22 15-MAY-17
        22 16-MAY-17
        22 22-MAY-17
        23 23-MAY-17
        23 25-MAY-17
        23 30-MAY-17

8 rows selected.

SQL> select id, count(diff)+1 count 
     from( 
          select id, dt - lag(dt) over(order by dt) diff 
          from mytest
          ) 
     where diff >= 5 
     group by id;

        ID         COUNT
---------- -------------
        22             2
        23             2

Here is the fiddle.

For more about LAG()

Documentation: LAG

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.