Link: Query (duration) different between data value change
I am trying to write a query that would get me the duration of a status in a table. This query needs to work in SQL Server 2008.
Say I have the following table:
CREATE TABLE RateTable(
[Key] [int],
[Value] varchar(10) NULL,
[RecordDate] [DateTime] NULL
)
GO
INSERT INTO [RateTable] VALUES (1,'abc','2012-01-01');
INSERT INTO [RateTable] VALUES (1,'abc','2012-01-02');
INSERT INTO [RateTable] VALUES (1,'xyz','2012-01-02');
INSERT INTO [RateTable] VALUES (1,'xyz','2012-01-05');
INSERT INTO [RateTable] VALUES (1,'abc','2012-01-05');
INSERT INTO [RateTable] VALUES (1,'abc','2012-01-08');
INSERT INTO [RateTable] VALUES (2,'abc','2012-01-10');
INSERT INTO [RateTable] VALUES (2,'abc','2012-01-11');
INSERT INTO [RateTable] VALUES (2,'abc','2012-01-12');
GO
So it contains the rows that follow:
Key Value RecordDate
--- ----- ----------
1 abc 2012-01-01
1 abc 2012-01-02
1 xyz 2012-01-02
1 xyz 2012-01-05
1 abc 2012-01-05
1 abc 2012-01-08
2 abc 2012-01-10
2 abc 2012-01-11
2 abc 2012-01-12
I would like to have output (the result set) for the value 'abc'
only, as shown below:
Value StartDate EndDate
----- ---------- ----------
1 2012-01-01 2012-01-02
1 2012-01-05 2012-01-08
2 2012-01-10 2012-01-12
Best Answer
Yet another grouping or window. It is a bit longer due SQL Server 2008 doesn't support LAG functions and it must be simulated.