2016-11-19 113 views
0

内的工作日数我有下列数据的表:MySQL的 - 日期范围

empid | officeid |  doj 
-------+----------+------------ 
    19 | 112 | 2012-05-06 
    26 | 112 | 2012-10-16 
    35 | 112 | 2014-05-01 
    17 | 112 | 2015-12-14 
    19 | 169 | 2016-10-07 
    26 | 146 | 2015-08-07 
    42 | 102 | 2016-06-07 
    35 | 135 | 2016-10-15 
    26 | 112 | 2016-10-20 

(DOJ =加入的日期)。我需要得到员工的一份报告,在办公室工作的天数,对于一个特定的时期。例如,我想的办公室ID 1122016年10月的报告。所以结果应该是这样的:

empid | days 
-------+------- 
    35 | 14 (moved to another office on October 15th) 
    17 | 31 (complete month) 
    26 | 11 (October 20 to 31) 
    42 | 31 (complete month) 

雇员19不应该来,因为他现在不在办公室112。我试过的:

select sh.empid,datediff(
    greatest(last_day('2016-10-01'), 
    (select doj from servicehistory where empid=sh.empid and date<sh.date 
     order by date desc limit 1) 
    ),date 
) as days from servicehistory sh where sh.office='112' and date=(
    if(
     ((select count(date) from servicehistory where empid=sh.empid and 
      date between '2016-10-01' and '2016-10-31')>0), 
     (select date from servicehistory where empid=sh.empid and 
      date between '2016-10-01' and '2016-10-31' limit 1), 
     (select max(date) from servicehistory where empid=sh.empid and 
      office=sh.office and date<=last_day('2016-10-01')) 
    ) 
) 

但它没有给出预期的结果。这是给天超过31名员工目前不在办公室。

回答

1
select (case when tmp.doj<='2016-10-01' then DATEDIFF(last_day('2016-10-01'),'2016-10-01') 
else DATEDIFF(last_day('2016-10-01'),tmp.doj) end)as days,tmp.emp_id from (
select emp_id,max(doj)as doj from emp e group by emp_id)tmp 

尝试此操作并根据您的要求进行更改。

+0

感谢。有效。 –