I want convert data rows to date ranges in sql. below are sample data
#Slno MonthDate System#
1 7/1/2017 SystemA
1 8/1/2017 SystemA
1 9/1/2017 SystemB
1 10/1/2017 SystemB
1 11/1/2017 SystemB
1 12/1/2017 SystemA
1 1/1/2018 SystemA
1 2/1/2018 SystemA
1 3/1/2018 SystemB
2 12/1/2017 SystemA
2 1/1/2018 SystemB
3 2/1/2018 SystemA
4 3/1/2018 SystemB
and expected output is
#Slno StartDate EndDate System#
1 7/1/2017 8/1/2017 SystemA
1 9/1/2017 11/1/2017 SystemB
1 12/1/2017 3/1/2018 SystemA
2 12/1/2017 12/1/2017 SystemA
2 1/1/2018 1/1/2018 SystemB
3 2/1/2018 2/1/2018 SystemA
4 3/1/2018 3/1/2018 SystemB
You can do this using the "difference of row numbers" method:
The logic for this is a bit tricky. In my experience, you can run the subquery and stare at the results. You should be able to see how the difference of the row numbers defines the groups defined by equal values in adjacent rows.