I have a flat table which holds status updates.
These updates are stored in the following format:
AgreementID | StatusID | StatusDate
Source Data:
AgreementID StatusID StatusDate
109 1 14/01/2013 15:00:33
109 2 14/01/2013 15:01:28
109 2 14/01/2013 15:01:28
109 2 14/01/2013 15:02:42
109 2 26/02/2013 16:27:38
109 2 26/02/2013 16:27:45
109 8 19/02/2013 13:57:33
109 8 04/03/2013 16:46:29
109 8 18/03/2013 14:08:12
109 8 18/03/2013 14:47:00
109 8 18/03/2013 14:48:46
109 9 26/03/2013 15:41:51
What I am needing is to map an Agreement Status in Date Ranges, An agreement can have multiple status updates of the same StatusID, but once the agreement goes onto the next StatusID it cannot step backwards to the previous Status ID.
For the last Status the date range should be StatusDate To Date.
I have got the following piece of code, but the results are not giving me what I want...
SELECT
AgreementID,
CONVERT(datetime, CONVERT(varchar(10), StatusDate, 103), 103) AS StatusDate,
CONVERT(datetime, CONVERT(varchar(10), StatusDate, 103), 103) AS DateFrom,
CASE WHEN DateTo IS NULL THEN CONVERT(datetime, CONVERT(varchar(10), GETDATE(), 103), 103) ELSE CONVERT(datetime, CONVERT(varchar(10), DateTo, 103), 103) END AS DateTo,
StatusID
FROM
(
SELECT
AgreementID,
StatusID,
StatusDate,
(SELECT TOP (1) StatusDate FROM TblStatusUpdates AS SU WHERE SU.AgreementID = U.AgreementID AND SU.StatusDate > U.StatusDate ORDER BY StatusID, StatusDate ASC) DateTo,
RN = ROW_NUMBER() OVER (Partition BY AgreementID ORDER BY StatusDate)
FROM
(
SELECT
AgreementID,
StatusID,
MIN(StatusDate) AS StatusDate
FROM
TblStatusUpdates
GROUP BY
AgreementID, StatusID
) AS U
) AS A
Here is an example result from this query:
AgreementID StatusDate DateFrom DateTo StatusID
109 14/01/2013 14/01/2013 14/01/2013 1
109 14/01/2013 14/01/2013 14/01/2013 2
109 19/02/2013 19/02/2013 26/02/2013 8
109 26/03/2013 26/03/2013 25/04/2013 9
As you can see, the Date To Value is not right, it should always run to the day before the next status ID.
So in this example, then Status 2 Should run from 19/02/2013 TO 18/02/13
Any suggestions would be great. Thank you.