If the client just wants a rough estimate, I would start with the number of days for each stay, divided by 7 and rounded.
The trick is to build an active date with the corresponding Inactive date, and the best way I can do this is to select the Active and Inactive dates separately, rank them by date and combine them together with EmplID and rank. The analytic function ROW_NUMBER() is the best way to evaluate in this situation:
WITH EmpActive AS ( SELECT EmplID, EffDt, ROW_NUMBER() OVER (PARTITION BY EmplID ORDER BY EffDt NULLS LAST) DtRank FROM ps_job WHERE HR_Status = 'A' ), EmpInactive AS ( SELECT EmplID, EffDt, ROW_NUMBER() OVER (PARTITION BY EmplID ORDER BY EffDt NULLS LAST) DtRank FROM ps_job WHERE HR_Status = 'I' ) SELECT EmpActive.EmplID, EmpActive.EffDt AS ActiveDate, EmpInactive.EffDt AS InactiveDate, ROUND((NVL(EmpInactive.EffDt, TRUNC(SYSDATE)) - EmpActive.EffDt) / 7) AS WeeksActive FROM EmpActive LEFT JOIN EmpInactive ON EmpActive.EmplID = EmpInactive.EmplID AND EmpActive.DtRank = EmpInactive.DtRank
The third concert for EmplID = 1000 has an active date, but without an inactivity date, so NULLS LAST in the order of ROW_NUMBER and the left join is between two subqueries.
I used the "days / 7" math here; You can replace what you need when you hear a response from the client. Please note: if there is no corresponding inactive date, the request uses the current date.
Here's the SQLFiddle of this here .
source share