oracle - SQL to Find Number of Weeks an Employee Was Active Between Two Dates -
i have table list of dates employee became active/inactive , want count weeks employee active within date range.
so table (ps_job) have values this:
emplid effdt hr_status ------ ----- ------ 1000 01-jul-11 1000 01-sep-11 1000 01-jan-12 1000 01-mar-12 1000 01-sep-12
the query need show me number of weeks emplid active 01-jul-11 31-dec-12.
the desired result set be:
emplid weeks_active ------ ------------ 1000 35
i got number 35 adding results sqls below:
select (next_day('01-sep-11','sunday') - next_day('01-jul-11','sunday'))/7 weeks_active dual; select (next_day('01-mar-12','sunday') - next_day('01-jan-12','sunday'))/7 weeks_active dual; select (next_day('31-dec-12','sunday') - next_day('01-sep-12','sunday'))/7 weeks_active dual;
the problem can't seem figure out how create single query statement go through rows every employee within date range , return each emplid , number of weeks active. prefer use basic sql instead of pl/sql can transfer peoplesoft query can run user, willing run user using oracle sql developer if need be.
database: oracle database 11g enterprise edition release 11.2.0.3.0 - 64bit production
here i'm using lead
in subquery next date , summing intervals in outer query:
with q ( select emplid, effdt, hr_status , lead (effdt, 1) on (partition emplid order effdt) next_effdt ps_job order emplid, effdt ) select emplid , trunc(sum((trunc(coalesce(next_effdt, current_timestamp)) - trunc(effdt)) / 7)) weeks_active q hr_status = 'a' group emplid;
the coalesce
function grab system date in event cannot find matching i
record (employee current). substitute end of year if that's spec.
note i'm not doing rigorous testing see entries ordered a/i/a/i etc., might want add checks of nature if know data requires it.
feel free play @ sql fiddle.
Comments
Post a Comment