MySQL:计算具有导致给定日期的连续日期的行

时间:2014-01-21 15:04:48

标签: mysql sql

我有一张记录雇员工作班次的表格。它非常简单,包括(简化为简化):自动增量primary keyemployee_idjob_iddate

为每个轮班工作创建一行,因此如果某个特定员工在某一天没有工作,该员工在该日期将不会有任何行。

在某一天,我需要能够返回每个员工在当天工作的连续工作天数。

我不知道从哪里开始,并希望得到任何帮助。感谢

3 个答案:

答案 0 :(得分:4)

如果你有一系列数字,那么这些数字和一系列日期之间的差异将是不变的。我们可以使用此事实将工作日分组为具有最小和最大日期的组:

select employee_id, min(date) as mindate, max(date) as maxdate
from (select s.*, date_sub(date, interval seqnum days) as grp
      from (select s.*, (@rn := @rn + 1) as seqnum
            from shifts s cross join
                 (select @rn := 0) const
           ) s
     ) s
group by employee_id, grp;

一旦我们拥有了这个,那么将特定员工的特定日期延长到非常简单:

select employee_id,
       coalesce(datediff(XXX, 1+min(case when XXX between mindate and maxdate then mindate end)),
                0) as SequentialWorkingDays
from (select employee_id, min(date) as mindate, max(date) as maxdate
      from (select s.*, date_sub(date, interval seqnum days) as grp
            from (select s.*, (@rn := @rn + 1) as seqnum
                  from shifts s cross join
                       (select @rn := 0) const
                 ) s
           ) s
      group by employee_id, grp
     ) s
group by employee_id;

答案 1 :(得分:0)

假设您的表名为shift,则以下查询将为您提供所提供日期和当前日期之间的行数。

SELECT COUNT(`date`) AS working_days 
FROM `shift` 
WHERE `date` BETWEEN '2014-01-02' AND CURDATE()

答案 2 :(得分:0)

如果按排序的员工ID和日期的行号进行调整,您可以尝试计算实例,我认为它看起来像:

SELECT employee_id, job_id, date, days_worked = ROW_NUMBER() OVER (PARTITION BY employee_id, CAST(date) ORDER BY date)
FROM shifts