Emp_id Logdate
1 2016-05-04 11:10
1 2016-05-04 12:20
1 2016-05-04 13:10
1 2016-05-04 17:45
1 2016-05-04 18:10
1 2016-05-05 02:10
2 2016-05-04 13:10
2 2016-05-04 14:20
2 2016-05-04 15:10
2 2016-05-04 17:45
2 2016-05-04 18:10
2 2016-05-04 20:10
从上表中如何计算每天的总工作量。事情是员工我将在上午11点进入,并在下午2点离开。 从这个如何计算所有员工的工作时间......
答案 0 :(得分:0)
测试数据
Declare @t TABLE (Emp_id INT, Logdate Varchar(30))
INSERT INTO @t VALUES
(1 ,'2016-05-04 11:10'),
(1 ,'2016-05-04 12:20'),
(1 ,'2016-05-04 13:10'),
(1 ,'2016-05-04 17:45'),
(1 ,'2016-05-04 18:10'),
(1 ,'2016-05-05 02:10'),
(2 ,'2016-05-04 13:10'),
(2 ,'2016-05-04 14:20'),
(2 ,'2016-05-04 15:10'),
(2 ,'2016-05-04 17:45'),
(2 ,'2016-05-04 18:10'),
(2 ,'2016-05-04 20:10')
<强>查询强>
; WITH X AS(
Select Emp_id
, CONVERT(DATETIME, Logdate) AS Logdate
, ROW_NUMBER() OVER (PARTITION BY Emp_id
ORDER BY CONVERT(DATETIME, Logdate) ) rn
from @t
),Y AS(
SELECT Emp_id
,Logdate LogDateTime
,CASE WHEN rn % 2 =1 THEN 0
WHEN rn % 2 =0 THEN 1
END [InOut]
,CONVERT(DATE, Logdate) Logdate
,rn
FROM X
),WorkingHours AS (
SELECT Y.Emp_id
,Y.LogDateTime TimeIn
,YY.LogDateTime TimeOut
,DATEDIFF(MINUTE, Y.LogDateTime,YY.LogDateTime) *1.00 / 60.0 HoursWorked
,Y.Logdate DateWoked
FROM Y
LEFT JOIN Y AS YY ON Y.Emp_id = YY.Emp_id
AND Y.rn = YY.rn - 1
AND Y.InOut = 0
WHERE Y.InOut <> 1)
Select Emp_id
,CAST(ROUND(SUM(HoursWorked) ,2) AS DECIMAL(10,2)) TotalHours
,DateWoked
FROM WorkingHours
GROUP BY Emp_id, DateWoked
结果集
╔════════╦════════════╦════════════╗
║ Emp_id ║ TotalHours ║ DateWoked ║
╠════════╬════════════╬════════════╣
║ 1 ║ 13.75 ║ 2016-05-04 ║
║ 2 ║ 5.75 ║ 2016-05-04 ║
╚════════╩════════════╩════════════╝