sql - How to count consecutive days and group by year -


i want count consecutive days (rows) , easy (given answers similar questions). in data set have groups of consecutive rows dates such as:

1. 30/12/2010 2. 31/12/2010 3. 01/01/2011 4. 02/01/2011 

looks 1 group (4 consecutive days), split group 2 groups. when having:

1. 30/12/2010 2. 31/12/2010 3. 01/01/2011 4. 02/01/2011 5. 05/01/2011 6. 06/02/2011 7. 07/02/2011 

i see grouped 4 groups (not three):

1. 30/12/2010 2. 31/12/2010  3. 01/01/2011 4. 02/01/2011  5. 05/01/2011  6. 06/02/2011 7. 07/02/2011 

i'm using sql server 2014

you can number rows this:

declare @t table(id int, dt date);  insert @t values (1, '2010-12-30'), (2, '2010-12-31'), (3, '2011-01-01'), (4, '2011-01-02'), (5, '2011-01-05'), (6, '2011-02-06'), (7, '2011-02-07');  cte1 (     select *, year(dt) temp_year, row_number() on (order dt) temp_rownum     @t ), cte2 (     select cte1.*, datediff(day, temp_rownum, dt) temp_dategroup     cte1 ) select *, rank() on (order temp_year, temp_dategroup) final_rank cte2 order final_rank, dt 

result:

id  dt          temp_year  temp_rownum  temp_dategroup  final_rank 1   2010-12-30  2010       1            40539           1 2   2010-12-31  2010       2            40539           1 3   2011-01-01  2011       3            40539           3 4   2011-01-02  2011       4            40539           3 5   2011-01-05  2011       5            40541           5 6   2011-02-06  2011       6            40572           6 7   2011-02-07  2011       7            40572           6 

it possible use simplify query chose display columns easier understand. datediff trick copied from answer.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -