Here is an easy way to get started. This works for all effective and ending dates in your data:
select thedate, SUM(num) over (order by thedate) as numActives from ((select effective_start_date as thedate, 1 as num from hr.per_periods_of_service) union all (select effective_end_date as thedate, -1 as num from hr.per_periods_of_service) ) dates
It works by adding one person for each run and subtracting it for each end (via num ) and making a cumulative sum. This may have duplicate dates, so you can also perform aggregation to eliminate these duplicates:
select thedate, max(numActives) from (select thedate, SUM(num) over (order by thedate) as numActives from ((select effective_start_date as thedate, 1 as num from hr.per_periods_of_service) union all (select effective_end_date as thedate, -1 as num from hr.per_periods_of_service) ) dates ) t group by thedate;
If you really need all the dates, it's best to start with a calendar table and use a simple option in the original query:
select c.thedate, count(*) as NumActives from calendar c left outer join hr.per_periods_of_service pos on c.thedate between pos.effective_start_date and pos.effective_end_date group by c.thedate;
source share