我有这样的结构表
empid fromdate todate office_ID
1 2012-03-01 2014-04-2 1
1 2014-04-03 ---- 2
2 2012-03-01 2014-04-2 2
3 2012-03-01 2014-04-2 1
我想在某个月从这个表中获取它 例如。 5 月 205 员工 1 在哪里 为此我设计了查询
select* from tbl_emp_office where (year(From_date)*100+ month(From_date)) < '201505'
但它并没有为所有用户提供正确答案
如果员工目前在某个办公室工作,那么 todate 将是未知的,因此它为空(如果您提出更好的建议,可以更改此逻辑)
最佳答案
如果我没理解错的话,你想要这个:
select office_id
from employee_history
where year(fromdate) <= 2015
and month(fromdate) <= 5
and (
(month(todate) >= 5 and year(todate) >= 2015)
or todate is null
)
and empid = 1;
查询使用 mysql 函数将日期分解为年月,然后确保您要查找的年月等于或晚于它们的开始日期,并且它们的 todate 为空,或者出现在您正在寻找的月/年组合。
这还应该包括他们在部分月份所在的办公室。
关于mysql - 根据时间跨度获取正确的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29411755/