I have a table with the following structure
| ChangedDate | IDParameter | ChangedTo (column bit) |
So I need to get time intervals when my parameter is True or False, like the following
| IDParameter | ChangedToDate1 | ChangedToDate2 | ChangedTo (true for false || false to true)
and i do
With RankedDates As
(
Select T1.[ChangedDate], T1.ID, T1.[ChangedToValue]
, Row_Number() Over( Partition By T1.ID Order By T1.[ChangedDate] ) As Num
From [Changes] As T1
)
SELECT T1.[ID]
,T2.[ChangedToValue]
,T1.[ChangedDate] AS startDate
,T2.[ChangedDate] AS endDate
FROM [RankedDates] AS T1
Join RankedDates As T2
On T2.ID = T1.ID
And T2.Num = T1.Num + 1
And T2.[ChangedToValue] <> T1.[ChangedToValue]
Order By T2.[ChangedDate]
The trouble is that I miss the first and last interval here. it must be NULL for the start date, if it is the first, and NULL for endDate for the last interval for each parameter identifier. I suppose I need to add it with UNION, but my problem cannot figure out how to add it for each IDParameter.
, , , , NULL NULL maxdate .
ms sql server 2008
.
:
08.03.2011 ID1 0 -> 1
09.03.2011 ID1 1 -> 0
09.03.2011 ID2 0 -> 1
10.03.2011 ID1 0 -> 1
10.03.2011 ID2 1 -> 0
--- >
NULL , 08.03.2011 ID1 is 0
NULL , 09.03.2011 ID2 is 0
08.03.2011, 09.03.2011 ID1 is 1
09.03.2011, 10.03.2011 ID2 is 1
09.03.2011, 10.03.2011 ID1 is 0
10.03.2011, NULL ID1 is 1
10.03.2011, NULL ID2 is 0