2015-08-17 38 views
0

我想,如果員工不在連續兩天表現着色,所以我寫像查詢 -連續型的日期範圍在SQL Server

select employee,attendancedate, 

(select (case when count(employee) >= 3 then 1 else 0 end) 
    from att_tblextattendance 
where employee = a.employee and session1status=5 and session2status=5 
and attendancedate between dateadd(day,-3,'2014-05-30 00:00:00.000') and '2014-05-30 00:00:00.000') as bCount, 

(select (case when count(employee) >= 3 then 1 else 0 end) 
from att_tblextattendance 
where employee = a.employee and session1status=5 and session2status=5 
and attendancedate between '2014-05-30 00:00:00.000' and dateadd(day,3,'2014-05-30 00:00:00.000')) as fCount 

from att_tblextattendance a where employee=498 and (session1status=5 or session2status=5) 

這裏,如果員工沒有連續3天然後bcount或FCOUNT應該是1,否則0,但這裏的問題是如果員工連續不存在,那麼上面的選擇日期範圍內的問題也是bcount更新爲1.上面的查詢結果。 行是員工,attendancedate,bcount和fcount。

498  2013-07-25 00:00:00.000 1  0 
    498  2013-07-26 00:00:00.000 1  0 
    498  2014-05-27 00:00:00.000 1  0 
    498  2014-05-29 00:00:00.000 1  0 
    498  2014-05-30 00:00:00.000 1  0 

預期輸出 -

498  2013-07-25 00:00:00.000 1  0 
    498  2013-07-26 00:00:00.000 1  0 
    498  2014-05-27 00:00:00.000 1  0 
    498  2014-05-29 00:00:00.000 0  0 
    498  2014-05-30 00:00:00.000 0  0 

,請給我一些建議,我應該怎麼檢查的日期在日期範圍是連續的。

+0

請提供預期的輸出。 –

+0

感謝您的回覆,我已更新我的問題。 – Basavaraj

+0

您的問題尚不清楚。解釋日期列存儲的情況,以及清楚地計算2個布爾列值的方式。 – DarkKnight

回答

1

你可以嘗試以下方法:

WITH cnts AS (
    SELECT att-row_number() OVER (PARTITION BY emp ORDER BY att) diff, 
    * from #tbl 
), grp AS ( 
    SELECT emp em,count(*) cnt,min(att) att1, max(att) att2 
    FROM cnts GROUP BY emp,diff) 
SELECT emp,att,CASE WHEN cnt>2 THEN 1 ELSE 0 END bcnt, fcnt 
FROM #tbl t INNER JOIN grp ON em=emp AND att between att1 and att2 
ORDER BY att 

在這裏看到一個live demo

這將爲您提供所有員工ID的列表。這裏的基本技巧是,我在group by之間差異diff之間的出席日期和每個員工row_number()。如果差異保持不變,那麼這些行是具有連續日期的行。我不確定,你想在欄目fcnt中顯示什麼,所以在我的示例中,這些列保持不變(0)。

+0

謝謝你對我有用。 – Basavaraj