我从这个论坛得到了以下代码。它从员工出勤中检索数据,如:
userid dateandtime checktype
1. 100 01/01/2015 I
2. 100 01/01/2015 O
3. 102 02/02/2015 I
4. 102 02/02/2015 O
现在我想检索两个特定日期之间的所有数据,但是即使缺少一个日期也应检索所有日期,这些日子应该在小时栏中显示空白或零
SELECT t.UserID ,
[Date] = DATEADD(dd, 0, DATEDIFF(dd, 0, t.CheckIn)) ,
CheckIn = CONVERT(VARCHAR(10), t.CheckIn, 108) ,
CheckOut = CONVERT(VARCHAR(10), t.CheckOut, 108) ,
[Hours] = CAST(DATEDIFF(MINUTE, t.CheckIn, t.CheckOut) / 60. AS DECIMAL(10,
2))
FROM ( SELECT t.UserID ,
CheckIn = t.Checktime ,
CheckOut = r.Checktime ,
RowNum = ROW_NUMBER() OVER ( PARTITION BY t.UserID,
r.Checktime ORDER BY 1 / 0 )
FROM CHECKINOUT t
OUTER APPLY ( SELECT TOP 1
*
FROM CHECKINOUT t2
WHERE t2.UserID = t.UserID
AND t2.Checktime > t.Checktime
AND DATEADD(dd, 0,
DATEDIFF(dd, 0,
t.Checktime)) = DATEADD(dd,
0,
DATEDIFF(dd, 0,
t2.Checktime))
AND t2.Checktype = 'O'
ORDER BY t2.Checktime
) r
WHERE t.Checktype = 'I'
) t
WHERE t.RowNum = 1