Below is the data in my Source table:
Report_Date AccountNumber eventtype
**1/1/2017 500000001 2
1/2/2017 500000001 2
1/3/2017 500000001 2**
**1/4/2017 500000001 1
1/5/2017 500000001 1**
**1/6/2017 500000001 2
1/8/2017 500000001 2
1/9/2017 500000001 2
1/10/2017 500000001 2
1/11/2017 500000001 2**
**1/12/2017 500000001 1
1/13/2017 500000001 1
1/15/2017 500000001 1
1/16/2017 500000001 1
1/17/2017 500000001 1**
**1/18/2017 500000001 2
1/19/2017 500000001 2
1/20/2017 500000001 2**
My sql server query output needs to be like:
AccountNumber eventtype StartDt EndDt
500000001 2 1/1/2017 1/3/2017
500000001 1 1/4/2017 1/5/2017
500000001 2 1/6/2017 1/11/2017
500000001 1 1/12/2017 1/17/2017
500000001 2 1/18/2017 1/20/2017
I have tried a lot using all possible combinations using RANK, ROW_NUMBER, DENSE_RANK etc. But struggling to get the desired output. Any help will be highly appreciated.
The query I'm using is:
Select a.*,
row_number() Over (partition by eventtype ORDER BY aCCOUNTnUMBER,eventtype) as rank
from
(
SELECT
[Report_Date],
[AccountNumber],
case when [DelqLevel] > 0 Then '1'
Else '2' End as eventtype
FROM tab
where
[AccountNumber] = '500000001'
)a
Order by 2,1
This is a gaps-and-islands problem. One solution is the difference of row numbers -- which happily works in SQL Server 2008:
Why this works is a little tricky to explain. But if you look at the results of the subquery, you'll see how the difference in the two row number values identifies "adjacent" records with the same event type.