MySQL-如何查找每行之间的差异日期

时间:2018-07-08 13:03:35

标签: mysql sql

编程大师,

我需要帮助。这是员工数据,NULL中的TerminationDate是指当前日期,表示该员工仍在工作。 我需要找到没有人被雇用或终止的最长时间(以天为单位)。

表名称:Employee 列名称:IDHireDateTerminationDate

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

我已经制定了需要做什么的过程

  1. 合并HireDateTerminationDate中的数据(应该有18行)
  2. 订购日期
  3. 找到Row(n)和Row(n-1)中每个日期之间的差异
  4. 获得最大差异

但是我不知道如何在MySQL中做到这一点,或者甚至不可能。我想知道是否还有其他方法?请帮助我

1 个答案:

答案 0 :(得分:0)

在版本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()替换为您考虑的任何截止日期来进行调整。如果您不希望使用最近的时间段,请在外部查询中添加where next_dte is not null

相关问题