MSSQL 處理連續出勤天數

2020-09-17  本文已影响0人  dlj_li

Empno(工號),attdate(出勤日期),OnTime(打卡時間),ShiftTime(排班時間),rank(打卡時間排序),第一步:先獲取用戶在一段時間的打卡排名,結果如下:

select empno,attdate,OnTime,ShiftTime,row_number() over(partition by empno order by OnTime) rank

from

FactAllatthrs

where ontime is not null and ShiftTime is not null

1

第二步:

獲取每個打卡日期中的日與rank之間的差:

select t.empno,t.OnTime,rank,day(t.OnTime) days,day(t.OnTime)-t.rank as day_cha

from (

select empno,attdate,OnTime,row_number() over(partition by empno order by OnTime) rank

from

FactAllatthrs

where  ontime is not null and ShiftTime is not null)t

2

看上面的結果表,發現,連續打卡日期的day_cha 都是相等的,這樣獲取連續打卡的天數就容易了。连续打卡天数是截止目前最近的一个 连续打卡天数还是历史坚持最长的打卡天数

所有的打開天數:

select empno, month,

count(day_cha) days

from

(select t.empno,t.attdate,left(t.attdate,6) as month ,t.OnTime,Month(t.ShiftTime) mm ,t.rank,day(t.OnTime)-t.rank as day_cha

from (

select empno,attdate,OnTime,ShiftTime,row_number() over(partition by empno order by OnTime) rank

from

FactAllatthrs

where ontime is not null and ShiftTime is not null)t

) t2 group by empno,day_cha,month

由此可見此用戶最近的連續出勤是15天,而歷史上最長的連續出勤也為15天

綜上所得:要獲取最近的連續打卡天數,就把day_cha 中的最大值對應的days取出來;如果要獲取歷史上最的,只要把最大的days取出來就OK了

附:直接算最近的連續出勤

select max(A.ShiftTime) ontime, datediff(day,max(A.ShiftTime),getdate()) as days ,A.empno from FactAllatthrs A,FactDLeave B

where A.ontime is  null and A.ShiftTime is not null  and B.Udate=convert(nvarchar(11),getdate()-1,112) and B.Emplid=A.empno  group by A.empno

上一篇 下一篇

猜你喜欢

热点阅读