sql server 2008 - SQL Database Date Ranges -
i have flat table holds status updates.
these updates stored in 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 needing map agreement status in date ranges, agreement can have multiple status updates of same statusid, once agreement goes onto next statusid cannot step backwards previous status id.
for last status date range should statusdate date.
i have got following piece of code, results not giving me want...
select agreementid, convert(datetime, convert(varchar(10), statusdate, 103), 103) statusdate, convert(datetime, convert(varchar(10), statusdate, 103), 103) datefrom, case when dateto null convert(datetime, convert(varchar(10), getdate(), 103), 103) else convert(datetime, convert(varchar(10), dateto, 103), 103) end dateto, statusid ( select agreementid, statusid, statusdate, (select top (1) statusdate tblstatusupdates su su.agreementid = u.agreementid , su.statusdate > u.statusdate order statusid, statusdate asc) dateto, rn = row_number() on (partition agreementid order statusdate) ( select agreementid, statusid, min(statusdate) statusdate tblstatusupdates group agreementid, statusid ) u )
here example result 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 can see, date value not right, should run day before next status id.
so in example, status 2 should run 19/02/2013 18/02/13
any suggestions great. thank you.
quick update on one, trying far on complicated answer needed.
here code have got now:
select agreementid, statusid, datefrom, case when dateto not null dateadd(s, -1, dateto) else getdate() end dateto ( select agreementid, statusid, min(convert(datetime,statusdate,103)) datefrom, (select top(1) statusdate tblstatusupdates b b.statusid > a.statusid order statusid asc, statusdate asc) dateto tblstatusupdates group agreementid, statusid ) c
this gives me following results:
agreementid statusid datefrom dateto 109 1 2013-01-14 15:00:33.360 2013-01-14 15:01:27.393 109 2 2013-01-14 15:01:28.393 2013-02-19 13:57:32.437 109 8 2013-02-19 13:57:33.437 2013-03-26 15:41:49.843 109 9 2013-03-26 15:41:50.843 2013-04-26 10:34:13.860
thank suggestions.