I have audit data captured over time points which I would like to aggregate up to display where the value was the same over a period of time using SQL Server 2014.
Taking the below example data
I would like to transpose it to this ideally without using a cursor - you will see that the output is recording the time period where the value is the same and as such, the same value can be repeated over different periods (seen in rows 3 and 6).
I have been looking at LEAD()
and LAG()
as potential solutions, however I cannot fathom out how to make this work in order to band by time for the same value
Any direction would be gratefully received
In case the column [value] doesnt contain distinct number, you can use this query
SELECT start,end,value
FROM (SELECT MIN(ts) start
,MAX(ts) end
,value
,C
FROM (SELECT ts
,value
,(ROW_NUMBER() OVER (ORDER BY ts)
- ROW_NUMBER() OVER (PARTITION BY value ORDER BY ts)) C
FROM YourTable) x
GROUP BY value,C) y ORDER BY start