Regarding my table as below
WORKING_CALENDAR_TABLE
===================================================
EMPLOYEE ID | DATE | WORKING DAY (0: Holiday; 1: WORKING DAY)
===================================================
02661 2017/12/01 1
02661 2017/12/02 1
02661 2017/12/03 0
02661 2017/12/04 0
02661 2017/12/05 0
02661 2017/12/06 1
02661 2017/12/07 1
02661 2017/12/08 1
02661 2017/12/09 1
2017/12/10时,我的预期结果如下
===================================================
EMPLOYEE ID | CONTINOUS WORKING DAY
===================================================
02661 4
如果我们使用SQL ORACLE,我们是否可以利用SQL ORACLE获得此结果?
答案 0 :(得分:0)
这样做的一种方法可以是:
2017/12/10
)之前的最后一天。以下是包含一些注释的代码:
Select employee_id, count(*) as continuous_days from mytable
where employee_id = '02661' and date > (select max(date)
where employee_id ='02661' and working_day = 0 and date date <
'2017/12/10') and date <
'2017/12/10' group by employee_id
/* (select max(date)
where employee_id ='02661' and working_day = 0 and date <
'2017/12/10') gets the last day where the employee didn't work before the reference date. Each row from a date after max(date) represent a working day for the employee because all of them are going to to have working_day = 1*/
有待改进的地方:
如果员工在参考日期之前没有假期,那么
select max(date)
where employee_id ='02661' and working_day = 0 and date date <
'2017/12/10'
将返回null
,因此您可以使用COALESCE
来防止错误,如果是null,则会获得一些其他值作为回报。我认为在你的情况下,它可以在很早的时候就足够了。你可以这样使用它:
COALESCE( (select max(date)
where employee_id ='02661' and working_day = 0 and date <
'2017/12/10'), '1900-01-01')
,完整的查询将是:
select employee_id, count(*) as continuous_days from mytable
where employee_id = '02661' and date > COALESCE( (select max(date)
where employee_id ='02661' and working_day = 0 and date <
'2017/12/10'), '1900-01-01') and date <
'2017/12/10' group by employee_id
答案 1 :(得分:0)
对于给定日期,最通用的解决方案是:
select employee_id, count(*)
from t
where employee_id = '02661' and
date < date '2017-12-10' and
date > (select max(t2.date)
from t t2
where t2.employee_id = t.employee_id and t2.date < date '2017-12-10'
);
答案 2 :(得分:0)
您可以尝试此查询:
SELECT T.EMPLOYEE_ID,
COUNT(0) AS CONTINUOUS_DAYS
FROM WORKING_CALENDAR_TABLE T
WHERE T.WORK_DATE BETWEEN (SELECT MAX(WORK_DATE) + 1
FROM WORKING_CALENDAR_TABLE I
WHERE I.EMPLOYEE_ID = T.EMPLOYEE_ID
AND I.WORK_DAY = 0)
AND DATE '2017-12-10' + 1
GROUP BY T.EMPLOYEE_ID