使用MYSQL获取连续3天和5天或更长时间缺勤的员工列表

时间:2018-10-17 12:20:07

标签: mysql sql

试图确定连续缺勤> = 5天或= 3天(周末除外)的员工列表。

我的SQL数据库缺勤表如下

  @Provides
  @Singleton
  fun worksRepository(@Named("Api") api: Api, @Named("ApiAuth") api2: ApiAuth): IWorksRepository {
        return WorksRepository(api, api2)
    }

我正在寻找与以下类似的结果。

EMPLOYEE_ID HOURS_ABSENT    DATE
x1  7.500000    2017-01-16 00:00:00.000
x1  7.500000    2017-01-30 00:00:00.000
x1  7.500000    2017-01-31 00:00:00.000
x1  7.500000    2017-02-01 00:00:00.000
x1  7.500000    2017-02-02 00:00:00.000
x1  7.500000    2017-02-03 00:00:00.000
x1  7.500000    2017-02-06 00:00:00.000
x1  7.500000    2017-02-07 00:00:00.000
x1  7.500000    2017-05-22 00:00:00.000
X2  7.500000    2016-11-29 00:00:00.000
X2  7.500000    2016-11-30 00:00:00.000
X2  7.500000    2016-12-01 00:00:00.000

3DAYS和5DAYS标志应根据条件在开始日期设置为1。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

这里有点类似...

DROP TABLE IF EXISTS absentees;

CREATE TABLE absentees
(employee_id INT NOT NULL
,date DATE NOT NULL
,PRIMARY KEY(employee_id,date)
);

INSERT INTO absentees VALUES
(1,'2017-01-16'),
(1  ,'2017-01-30'),
(1  ,'2017-01-31'),
(1  ,'2017-02-01'),
(1  ,'2017-02-02'),
(1  ,'2017-02-03'),
(1  ,'2017-02-06'),
(1  ,'2017-02-07'),
(1  ,'2017-05-22'),
(2  ,'2016-11-29'),
(2  ,'2016-11-30'),
(2  ,'2016-12-01'); 

SELECT employee_id
     , MIN(date) date
     , MAX(i) days
  FROM 
     ( SELECT x.*
            , CASE WHEN @prev_employee_id = employee_id THEN CASE WHEN @prev_date = date - INTERVAL 1 DAY THEN @i:=@i+1 ELSE @i:=1 END ELSE @i:=1 END i
            , CASE WHEN @prev_employee_id = employee_id THEN CASE WHEN @prev_date = date - INTERVAL 1 DAY THEN @j:=@j ELSE @j:=@j+1 END ELSE @j:=1 END j
            , @prev_employee_id := employee_id prev_employee_id
            , @prev_date := date prev_date
         FROM absentees x
         JOIN (SELECT @prev_employee_id :='',@prev_date:='',@i:=0,@j:=0) vars
        ORDER
           BY employee_id
            , date
     ) a
 GROUP
    BY employee_id
     , j
HAVING days >= 3;

+-------------+------------+------+
| employee_id | date       | days |
+-------------+------------+------+
|           1 | 2017-01-30 |    5 |
|           2 | 2016-11-29 |    3 |
+-------------+------------+------+