我有一个表,其数据类似于下面
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
我想获得一个日期范围(例如最近3个月)之间的雇员列表,这些雇员连续5天在代码W中工作,并且在输出中包含该日期范围。每位员工一天可以有多个使用不同代码的记录。
预期输出为
Emp Date-Range --- ---------- E1 11/1 -11/5
下面是我尝试过的方法,但与我寻求的输出完全不符
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;
如果Emp E1已连续工作10天,则应在输出中将他列出两次,并同时列出两个日期范围。如果E1连续工作了9天(11/1至11/9),则应只列出一次,日期范围为11/1至11/9。
我已经看到过类似的问题,但没有一个问题适合我。我的数据库是Oracle 10G,没有PL / SQL。
我不确定我是否正确理解了所有内容,但是类似这样的内容可能会让您入门:
select emp, sum(diff) as days, to_char(min(workdate), 'yyyy-mm-dd') as work_start, to_char(max(workdate), 'yyyy-mm-dd') as work_end from ( select * from ( select emp, workdate, code, nvl(workdate - lag(workdate) over (partition by emp, code order by workdate),1) as diff from tablename where code = 'W' and workdate between ... ) t1 where diff = 1 -- only consecutive rows ) t2 group by emp having sum(diff) = 5
SQLFiddle:http ://sqlfiddle.com/#!4/ad7ae/3
请注意,我使用workdate而不是,date因为使用保留字作为列名是一个坏主意。
workdate
date