在SQL Server中没有任何标志的情况下从多个值计算时间差

时间:2016-05-12 06:27:05

标签: sql-server

我需要计算员工休息时间,此处显示的样本:

Userid  Date_time       
------  ---------    
1001    9/1/15 10:31 AM 
1001    9/1/15 11:51 AM 
1001    9/1/15 11:58 AM 
1001    9/1/15 2:02 PM  
1001    9/1/15 2:38 PM  
1001    9/1/15 4:37 PM  
1001    9/1/15 5:12 PM 
1001    9/1/15 6:32 PM 
1001    9/1/15 6:34 PM
1001    9/1/15 7:39 PM  
1001    9/1/15 7:42 PM 
1001    9/1/15 7:53 PM  

因此,我不想要第一个和最后一个记录,因为它将按总工时计算。

预期结果:

Userid break_time_MIN 
------ -------------- 
1001   83    

请建议我如何计算每位员工的休息时间。

2 个答案:

答案 0 :(得分:1)

首先,您要删除第一行和最后一行。之后,您希望将两个连续的行分组,然后获得它们的不同。最后,计算所有差异的SUM

WITH Cte AS(
    SELECT *,
        grp = rn - (rn % 2 + 1)
    FROM (
        SELECT *,
            rn = ROW_NUMBER() OVER(PARTITION BY Userid ORDER BY Date_time),
            rnd = ROW_NUMBER() OVER(PARTITION BY Userid ORDER BY Date_time DESC)
        FROM #tbl
    ) t
    WHERE rn <> 1 AND rnd <> 1
),
CteFinal AS(
    SELECT
        Userid,
        BreakDuration = DATEDIFF(MINUTE, MIN(Date_time), MAX(Date_time))
    FROM Cte
    GROUP BY
        Userid, grp
)
SELECT
    Userid,
    break_time_MIN = SUM(BreakDuration)
FROM CteFinal
GROUP BY UserId;

ONLINE DEMO

--------------------- 
Result:
--------------------- 
Userid break_time_MIN 
------ -------------- 
1001   83    

答案 1 :(得分:0)

;WITH cte AS (
SELECT  Userid,
        Date_time,
        ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY UserId, Date_time) as RN
FROM YourTableName)

SELECT r1.Userid, SUM(DATEDIFF(MINUTE,r1.Date_time,r2.Date_time)) as break_time
FROM cte r1
INNER JOIN cte r2 
    ON r1.Userid = r2.Userid AND r1.RN + 1 = r2.RN
WHERE r1.RN % 2 = 0
GROUP BY r1.Userid

输出:

Userid  break_time
1001    83