Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hey guys I am totally stuck on a task I need to complete...I have an enrollment table that contains peoples "coverage". If you were to open the table it would look like something belowPersonID Name StartDt EndDt CovGap123456 John Doe 1/1/2008 NULL NULL123456 John Doe 1/15/2007 12/31/2007 1123456 John Doe 1/1/2006 12/31/2006 16987654 Jane Doe 2/1/2008 NULL NULL987654 Jane Doe 12/31/2006 12/31/2007 NULL654321 Monica Doe 1/1/2009 NULL NULLI need to figure out the CovGap which is going to be the difference in days between their EndDt and their NEXT StartDt. So for John Doe I would need to take his oldest coverage Enddt which is 12/31/2006 and see how many days are between that and the next StartDt which for him would be 1/15/2007. This is some new coding so I don't have anything to go off of and I am not even sure where to begin. Thanks a lot guys
russell
Pyro-ma-ni-yak
5072 Posts
Posted - 2009-12-04 : 14:55:31
Here's one way:
With policies (id, personid, name, startdt, enddt)as ( select row_number() over(partition by personid order by startdt), personid, name, startdt, enddt from yourTable)update yourTableset CovGap = datediff(day, old.enddt, new.startdt)from yourTable tjoin policies oldon old.personid = t.personidand old.enddt = t.enddtjoin policies newon new.personid = old.personidand new.id = old.id + 1