I have a list of dates like this (no gaps, each calendar date):
| DateKey | Valid |
|---|---|
| 2021-01-01 | 1 |
| 2021-01-02 | 1 |
| 2021-01-03 | 1 |
| 2021-01-04 | 0 |
| 2021-01-05 | 0 |
| 2021-01-06 | 1 |
| 2021-01-07 | 1 |
I would like to convert them using T-SQL to date ranges considering valid dates only.
So the results would be:
| ValidFrom | ValidTo |
|---|---|
| 2021-01-01 | 2021-01-03 |
| 2021-01-06 | 2021-01-07 |
Grouping simply by Valid flag rtutns wrong results:
select min(dateKey),max(dateKey)
from #t
group by Valid
If I knew how to assign a unique value for each continuous segment of valid dates, that would solve my problem. Is there anyone that can help me with this?