I have the following table:
ID Rating Rating_from Rating_to
1 2 2010-01-01 2011-01-01
1 2 2011-01-02 2012-02-01
1 3 2012-02-02 2013-03-01
1 2 2013-03-02 2013-04-01
1 2 2013-04-02 9999-12-31
It contains a rating per ID, that is checked on an ad-hoc basis. Each time the rating is checked, the last row is given a Rating_to date, usually the day before the new rating, and a new row is entered with a Rating_from date of the actual day of the rating. The Rating_to is set to 9999-12-31 instead of NULL. ♀️ Often, the rating remains the same. At times, the rating changes. An ID may also over time receive a rating it used to have before.
How do I get the earliest Rating_from date and latest Rating_to date, per ID, per rating, without grouping ratings that have the same rating value, but are interspersed with other ratings?
I'm trying to get the following table:
ID Rating Rating_from Rating_to
1 2 2010-01-01 2012-02-01
1 3 2012-02-02 2013-03-01
1 2 2013-03-02 NULL
Using the data from above, I tried grouping by ID and Rating (and setting a MIN() and MAX() on the from and to fields), but then I would only get two rows, one for rating 2 and one for rating 3, even though there were two periods of rating 2.
I asked a colleague, he suggested using LAG() and LEAD(), but I'm not sure how that will help here. The data is in SQL Server 2017, and there are around a million IDs. Any suggestions are very welcome.
I have added the below TABLE CREATE script with real table data, hope that helps:
CREATE TABLE tbl(
id INT,
rating int,
rating_from DATE,
rating_to DATE
);
INSERT INTO tbl VALUES
(1, 2, '2014-05-23', '2015-04-13'),
(1, 2, '2015-04-14', '2015-06-02'),
(1, 2, '2015-06-03', '2016-05-31'),
(1, 2, '2016-06-01', '2018-03-22'),
(2, 1, '2016-06-01', '9999-12-31'),
(3, 3, '2016-06-01', '9999-12-31'),
(1, 2, '2018-03-23', '2018-08-06'),
(1, 3, '2018-08-07', '2018-08-21'),
(1, 2, '2018-08-22', '2018-09-19'),
(1, 2, '2018-09-20', '9999-12-31');