I have a database with a list of jobs; for instance, it could be the list of previous work experiences in a CV. I would like to know how many days a person has been employed; so, I wrote this query:
SELECT sum(datediff(dd,isnull(date_begin,getdate()),isnull(date_end,getdate()))+1)
FROM jobs
WHERE person_id=X
Problem is, sometimes these dates overlap. Example:
person date_from date_to Comment
John 01-Jan-2011 31-Dec-2012 Two years working at ABC
John 01-Jan-2012 31-Dec-2013 Two years of extra work at evening
In this case my query would return 4 years, but I would like to return only 3. In other words, if a person has 2 jobs for one year I want it to count as 1 year, not as 2 years. The overlapping jobs could be any number, not just 2. I tried adjusting the query by subtracting the total duration of all the overlaps, which would work well with 2 overlapping jobs, but this would fail if there are more.