首页 > 解决方案 > sql如何在timein超时之间获取员工的先进性

问题描述

我试图使用 SQL 查询来获得员工的第一批。

这就是我想要做的。假设我有这张桌子:

employee_id | timeinout          
2           | 2019-02-22 02:10:00.000
2           | 2019-02-22 08:30:00.000
2           | 2019-02-22 09:10:00.000
3           | 2019-02-22 08:45:00.000
3           | 2019-02-22 10:30:00.000
3           | 2019-02-22 18:10:00.000

早上 6 点到 9 点 15 分之间应计为先到,9 点 16 分之后为迟到。

注意:正如您在表格中看到的,2019-02-22 02:10:00.000 中的时间不计入第一个。

我可以通过执行此查询获得第一个。

select employee_id,min(timeinout) as timein, max(timeinout) as timeout
group by employee_id,cast(timeinout as date)


employee_id | timein                  | timeout
2           | 2019-02-22 02:10:00.000 | 2019-02-22 09:10:00.000
3           | 2019-02-22 08:45:00.000 | 2019-02-22 18:10:00.000

我怎样才能得到这个结果:

employee_id | timein                  | timeout
2           | 2019-02-22 08:30:00.000 | 2019-02-22 09:10:00.000
3           | 2019-02-22 08:45:00.000 | 2019-02-22 18:10:00.000

标签: sql

解决方案


您需要使用case..when子句进行min聚合。

如果您正在使用MySQL,请尝试使用以下查询str_to_date

select employee_id,
       min( case when timeinout >= str_to_date('2019-02-22 06:10:00.000','%Y-%m-%d %h:%i:%s') 
                  and timeinout <  str_to_date('2019-02-22 09:16:00.000','%Y-%m-%d %h:%i:%s') 
                 then timeinout end ) as timein, 
       max(timeinout) as timeout 
  from shift 
 group by employee_id,cast(timeinout as date);

employee_id  timein                  timeout
2            2019-02-22 08:30:00     2019-02-22 09:10:00
3            2019-02-22 08:45:00     2019-02-22 18:10:00

Demo

如果您正在使用SQL Server,请尝试使用以下查询

convert( varchar, @val_date_time, 113 )

 select employee_id,
       min( case when timeinout >= convert( varchar, '2019-02-22 06:10:00.000', 113 ) 
                  and timeinout <  convert( varchar, '2019-02-22 09:16:00.000', 113 ) 
            then timeinout end ) as timein, 
        max(timeinout) as timeout 
   from shift
  group by employee_id,cast(timeinout as date);

employee_id  timein                      timeout
2            2019-02-22 08:30:00.000     2019-02-22 09:10:00.000
3            2019-02-22 08:45:00.000     2019-02-22 18:10:00.000

Demo


推荐阅读