SQL-员工休假日期跟踪

时间:2019-04-04 01:26:28

标签: sql

Emp id start date end date 
1. 1/14/18. 1/4/18 
1. 1/8/18. 1/8/18 
1. 1/11/18. 1/11/18 
1. 1/12/18. 1/12/18 
1. 1/13/18. 1/13/18 
1. 1/14/18. 1/14/18 
1. 1/15/18. 1/15/18 
1. 1/16/18. 1/16/18 
2. 1/1/18 1/13/18

如果1号员工从上表继续过去5天以上,我需要获取警报。因此,从第3行到第8行应该算在内。前两行不算在内。请帮助SQL。可能正在考虑创建循环。

3 个答案:

答案 0 :(得分:0)

您可以通过减去序列号来标识相邻日期的组。确切的语法取决于数据库,但是类似这样。

然后,您可以在组中进行计数:

select t.*,
       count(*) over (partition by emp_id, grp) as cnt
from (select t.*, 
             (start_date -
              row_number() over (partition by emp_id order by start_date) * interval '1 day'
             ) as grp
      from t
     ) t;

您可以将其用作子查询并添加where子句,例如where cnt >= 5以获取行。

答案 1 :(得分:0)

谢谢你,戈登。 它确实起作用,但是现在我想使用光标将这个查询放入循环中,这样它将按员工ID读取每条记录。我确实放过,但同样的6条记录正在重复。我认为我声明的循环方式有问题:

DECLARE @emp as varchar(20);
Declare @start as Date;
Declare @end as Date;
--Declare @date as Date;
DECLARE pstar2 CURSOR FOR
SELECT ApproveTime.[Employee ID],ApproveTime.[Start Date],ApproveTime.[End Date] 
from ApproveTime 
--where ApproveTime.[Employee ID]='JUF0036419' and
--ApproveTime.[Start Date]=ApproveTime.[End Date] 
--ApproveTime.[Employee ID]='36419'

open pstar2
--while loop
--EXIT when c1%NOTFOUND;
 FETCH next from pstar2 into @emp, @start, @end
 while (@@FETCH_STATUS=0)
 begin
select 
       count(*) over (partition by ApproveTime.[Employee ID], grp) as cnt, *
from (select t.*, 
             (t.[Start Date] -
              row_number() over (partition by t.[Employee ID] order by t.[Start Date]) * 1
             ) as grp
      from approvetime t
     ) approvetime where ApproveTime.[Employee ID]='36419'
     and  (ApproveTime.[Start Date] >='2018-01-01 00:00:00.000' and ApproveTime.[End Date]<='2018-01-31 00:00:00.000')
 print @emp 
 print @start
 print @end

 end
 --end
close pstar2
DEALLOCATE pstar2

答案 2 :(得分:0)

谢谢你,戈登。它确实起作用,但是现在我想使用光标将这个查询放入循环中,这样它将按员工ID读取每条记录。我确实放过,但同样的6条记录正在重复。我认为我声明的循环方式有问题:

DECLARE @emp as varchar(20);
Declare @start as Date;
Declare @end as Date;
--Declare @date as Date;
DECLARE pstar2 CURSOR FOR
SELECT ApproveTime.[Employee ID],ApproveTime.[Start Date],ApproveTime.[End Date] 
from ApproveTime 
--where ApproveTime.[Employee ID]='JUF0036419' and
--ApproveTime.[Start Date]=ApproveTime.[End Date] 
--ApproveTime.[Employee ID]='36419'

open pstar2
--while loop
--EXIT when c1%NOTFOUND;
 FETCH next from pstar2 into @emp, @start, @end
 while (@@FETCH_STATUS=0)
 begin
select 
       count(*) over (partition by ApproveTime.[Employee ID], grp) as cnt, *
from (select t.*, 
             (t.[Start Date] -
              row_number() over (partition by t.[Employee ID] order by t.[Start Date]) * 1
             ) as grp
      from approvetime t
     ) approvetime where ApproveTime.[Employee ID]='36419'
     and  (ApproveTime.[Start Date] >='2018-01-01 00:00:00.000' and ApproveTime.[End Date]<='2018-01-31 00:00:00.000')
 print @emp 
 print @start`enter code here`
 print @end

 end
 --end
close pstar2
DEALLOCATE pstar2