MySQL-如何查找每行之间的差异日期
嗨,编程大师 我需要帮助。这是一个员工数据,MySQL-如何查找每行之间的差异日期,mysql,sql,Mysql,Sql,嗨,编程大师 我需要帮助。这是一个员工数据,TerminationDate中的NULL表示当前日期,表示该员工仍在工作。 我需要找到最长的时间(以天为单位)没有人雇用或终止 表名:Employee 列名:ID,HireDate,TerminationDate Employee ID HireDate TerminationDate 1 2009-06-20 2016-01-01 2 2010-02-12 NULL 3 2012-03-14 NULL 4 2013-
TerminationDate
中的NULL
表示当前日期,表示该员工仍在工作。
我需要找到最长的时间(以天为单位)没有人雇用或终止
表名:Employee
列名:ID
,HireDate
,TerminationDate
Employee
ID HireDate TerminationDate
1 2009-06-20 2016-01-01
2 2010-02-12 NULL
3 2012-03-14 NULL
4 2013-09-10 2014-01-01
5 2013-09-10 NULL
6 2015-04-10 2015-05-01
7 2010-04-11 2016-01-01
8 2012-05-12 NULL
9 2011-04-13 2015-02-13
我已经制定了需要做什么的流程
HireDate
和TerminationDate
中的数据(它应该有18行)然而,我不知道如何在MySQL中实现它,或者它是否可能实现。我想知道是否还有其他方法?请帮助我在8版之前的MySQL中,这相当复杂。但你可以做到:
select dte, next_dte,
datediff(coalesce(next_dte, curdate()), dte) as diff
from (select dte,
(select min(d2.dte)
from ((select hiredate as dte
from t
) union -- intentionally remove duplicates
(select terminationdate as dte
from t
where teminationdate is not null
)
) d2
where d2.dte > d.dte
) next_dte
from ((select hiredate as dte
from t
) union -- intentionally remove duplicates
(select terminationdate as dte
from t
where teminationdate is not null
)
) d
) d
order by diff desc
limit 1;
请注意,这将根据当前日期查找最近的期间。您可以通过将curdate()
替换为您心目中的截止日期来调整此设置。如果不需要最新期间,请将其中next_dte不为null
添加到外部查询