I'm struggling with creating a query to rollup a date range whilst grouping contiguously by two fields - basically I'm trying to turn this:

```
|Key|Valid|DateFrom  |DateTo    |
|  1|    0|2001-01-01|2001-01-31|
|  1|    0|2001-02-01|2001-02-20|
|  1|    1|2001-02-21|2001-02-28|
|  1|    0|2001-03-01|2001-03-15|
|  2|    1|2001-01-01|2001-01-31|
|  2|    0|2001-02-01|2001-02-20|
|  2|    0|2001-02-21|2001-02-28|
|  2|    1|2001-03-01|2001-03-15|

```

into this:

```
|Key|Valid|DateFrom  |DateTo    |
|  1|    0|2001-01-01|2001-02-20|
|  1|    1|2001-02-21|2001-02-28|
|  1|    0|2001-03-01|2001-03-15|
|  2|    1|2001-01-01|2001-01-31|
|  2|    0|2001-02-01|2001-02-28|
|  2|    1|2001-03-01|2001-03-15|

```

Naturally a simple min(DateFrom), max(DateTo) group by Key, Valid doesn't work because it doesn't respect the chronological order of the date ranges. It should be noted there are no gaps in the date ranges within each key and valid group.

I've searched far and wide for solution (both here and elsewhere on the web) and found plenty of solutions for grouping dates using OVER and CTE's (tried them both) but I think the problem is that I'm trying to factor in two different groups. I've also tried converting the ranges to individual dates but again I can't seem to roll them up chronologically by two groups.

Any help would be appreciated. Thanks.