我有一张包含以下数据的表格:
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 =加入日期)。我需要在特定时期内获得一份员工的报告,其中包括在办公室工作的天数。例如,我想要 Office ID 112 的报告 2016年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天,员工目前不在办公室。
答案 0 :(得分: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
尝试此操作并根据您的要求进行更改。