I have a table has data similar to below
Emp Date Code
--- -------- ----
E1 11/1/2012 W
E1 11/1/2012 V
E2 11/1/2012 W
E1 11/2/2012 W
E1 11/3/2012 W
E1 11/4/2012 W
E1 11/5/2012 W
I want to get list of employees between a date range(say for the last 3 months) who worked for code W conescutively for 5 days with the date range in the output. Each employee can have multiple records for a single day with different codes.
Expected Output is
Emp Date-Range
--- ----------
E1 11/1 -11/5
Below is what I tried but I didn't come close at all to the output I seek
SELECT distinct user, MIN(date) startdate, MAX(date) enddate
FROM (SELECT user, date, (TRUNC(date) - ROWNUM) tmpcol
FROM (SELECT user, date
FROM tablename
where date between to_date('10/01/2012','mm/dd/yyyy') and to_date('10/03/2012','mm/dd/yyyy')
ORDER BY user, date) ot) t
GROUP BY user, tmpcol
ORDER BY user, startdate;
If Emp E1 has worked for 10 consecutive days, he should be listed twice in the output with both date ranges. If E1 has worked for 9 days consecutively(11/1 to 11/9), he should be listed only once with the date range 11/1 to 11/9.
I have already seen questions which are similar but none of them exactly worked out for me. My database is Oracle 10G and no PL/SQL.
I'm not sure I understood everything correctly, but something like this might get you started:
SQLFiddle: http://sqlfiddle.com/#!4/ad7ae/3
Note that I used
workdate
instead of thedate
as it is a bad idea to use a reserved word as a column name.Where table example is :
EMP(varchar2), date, 'W' or 'F'
You may start from here:
those rows with days_worked_last_5_days=5 are what you search.
See this fiddle.