テストデータ
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 ║
╚════════╩════════════╩════════════╝
どのバージョンのSQL Serverを使用していますか?従業員1と2の期待される成果は? –
これは最小/最大の質問かイン/アウトの質問ですか? –
従業員に休憩がありますか? –