I have been hitting a road block on a report I have been trying to create. I am looking to find the most recent consecutive months for a specific ID. If there is a break in the months the counter would restart. I have been able to create this but when there is a gap in the months my counter is not resetting.
Here is a sample table:
Declare @CTE Table (ID int, datestamp datetime); insert @CTE(ID, datestamp) select 8, '2013-11-15 00:00:00.000' union ALL select 8, '2013-12-16 00:00:00.000' union ALL select 8, '2014-01-15 00:00:00.000' union ALL select 15, '2013-09-16 00:00:00.000' union ALL select 17, '2014-02-28 00:00:00.000' union ALL select 51, '2013-05-10 00:00:00.000' union ALL select 51, '2014-04-10 00:00:00.000' union ALL select 52, '2013-12-26 00:00:00.000' union ALL select 59, '2013-08-12 00:00:00.000' union ALL select 59, '2014-01-13 00:00:00.000' union ALL select 59, '2014-04-14 00:00:00.000' union ALL select 59, '2014-05-12 00:00:00.000' union ALL select 62, '2013-06-10 00:00:00.000' union ALL select 62, '2013-06-20 00:00:00.000' union ALL select 62, '2013-10-10 00:00:00.000' union ALL select 62, '2013-11-12 00:00:00.000' union ALL select 64, '2013-05-28 00:00:00.000' union ALL select 64, '2013-06-27 00:00:00.000' union ALL select 64, '2013-07-29 00:00:00.000' union ALL select 66, '2013-07-26 00:00:00.000' union ALL select 74, '2013-04-15 00:00:00.000' union ALL select 74, '2013-05-15 00:00:00.000' union ALL select 82, '2013-09-03 00:00:00.000' union ALL select 92, '2013-04-15 00:00:00.000'
Here is my query I am having issues with.
WITH test AS ( SELECT ID, datestamp, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY datestamp) AS X FROM @CTE ) SELECT ID, COUNT(X) AS number_of_payments, MIN(datestamp) as Min_date, MAX(datestamp) as Max_date FROM test GROUP BY ID order by ID
I am looking for results as follows.
ID Count
8 3
15 1
17 1
51 1
52 1
59 2
62 2
64 3
66 1
74 2
82 1
92 1