I have a table like this:
CREATE TABLE Rates
(
RateGroup int NOT NULL,
Rate decimal(5, 2) NOT NULL,
DueDate date NOT NULL
);
This table contains rates which are valid from a certain due date to the day before the next due date. If no next due date is present, the rate's validity has no end. There can be multiple consecutive due days with the same rate and a certain can appear on different non consecutive due days as well.
The rates are divided into groups. A single due date can appear in multiple groups but only once per group.
Here's some example data:
INSERT INTO Rates(RateGroup, Rate, DueDate)
VALUES
(1, 1.2, '20210101'), (1, 1.2, '20210215'), (1, 1.5, '20210216'),
(1, 1.2, '20210501'), (2, 3.7, '20210101'), (2, 3.7, '20210215'),
(2, 3.7, '20210216'), (2, 3.7, '20210501'), (3, 2.9, '20210101'),
(3, 2.5, '20210215'), (3, 2.5, '20210216'), (3, 2.1, '20210501');
| RateGroup | Rate | DueDate |
|---|---|---|
| 1 | 1.20 | 2021-01-01 |
| 1 | 1.20 | 2021-02-15 |
| 1 | 1.50 | 2021-02-16 |
| 1 | 1.20 | 2021-05-01 |
| 2 | 3.70 | 2021-01-01 |
| 2 | 3.70 | 2021-02-15 |
| 2 | 3.70 | 2021-02-16 |
| 2 | 3.70 | 2021-05-01 |
| 3 | 2.90 | 2021-01-01 |
| 3 | 2.50 | 2021-02-15 |
| 3 | 2.50 | 2021-02-16 |
| 3 | 2.10 | 2021-05-01 |
Now I want a query which folds multiple consecutive rows of a rate group with the same rate to a single row containing the date range (start and end date) where the rate is valid.
This is the desired result:
| RateGroup | Rate | StartDate | EndDate |
|---|---|---|---|
| 1 | 1.20 | 2021-01-01 | 2021-02-15 |
| 1 | 1.50 | 2021-02-16 | 2021-04-30 |
| 1 | 1.20 | 2021-05-01 | NULL |
| 2 | 3.70 | 2021-01-01 | NULL |
| 3 | 2.90 | 2021-01-01 | 2021-02-14 |
| 3 | 2.50 | 2021-02-15 | 2021-04-30 |
| 3 | 2.10 | 2021-05-01 | NULL |
How can I achieve this?