查询计算在办公室度过的时间

时间:2017-01-22 14:17:25

标签: sql sql-server tsql

我有列表:姓名,进入办公室的日期和时间,退出的日期和时间

enter image description here

我必须编写查询,返回雇主每周在办公室花费的小时数,例如

enter image description here

我不知道怎么做,请帮忙。

1 个答案:

答案 0 :(得分:0)

测试数据

Declare @T TABLE (EmpID INT , Enter DATETIME , [Exit] DATETIME)

INSERT INTO @T VALUES
 (1 , '2017-01-22 09:26:00.000' , '2017-01-22 15:25:00.000')
,(1 , '2017-01-21 10:15:00.000' , '2017-01-21 12:00:00.000')
,(1 , '2017-01-20 09:05:00.000' , '2017-01-20 13:05:00.000')
,(1 , '2017-01-21 10:15:00.000' , '2017-01-21 12:00:00.000')
,(2 , '2017-01-22 09:26:00.000' , '2017-01-22 15:26:00.000')
,(2 , '2017-01-21 10:15:00.000' , '2017-01-21 12:30:00.000')
,(2 , '2017-01-20 09:05:00.000' , '2017-01-20 13:05:00.000')

<强>查询

Select EmpID
    , CONVERT(VARCHAR(10) ,DATEADD(DAY, -  (DATEPART(WEEKDAY, Enter)-1), Enter) , 104) [WeekStart]
    , CONVERT(VARCHAR(10) ,DATEADD(DAY, 7- (DATEPART(WEEKDAY, Enter)), Enter)   , 104)   [WeekEnd]
    , CAST(SUM(DATEDIFF(minute,Enter, [Exit])) / 60.00 AS DECIMAL(10,2)) [Hours Worked]

FROM @T 
GROUP BY EmpID
    , CONVERT(VARCHAR(10) ,DATEADD(DAY, -  (DATEPART(WEEKDAY, Enter)-1), Enter) , 104) 
    , CONVERT(VARCHAR(10) ,DATEADD(DAY, 7- (DATEPART(WEEKDAY, Enter)), Enter)   , 104)

结果集

╔═══════╦════════════╦════════════╦══════════════╗
║ EmpID ║ WeekStart  ║  WeekEnd   ║ Hours Worked ║
╠═══════╬════════════╬════════════╬══════════════╣
║     1 ║ 15.01.2017 ║ 21.01.2017 ║         7.50 ║
║     1 ║ 22.01.2017 ║ 28.01.2017 ║         5.98 ║
║     2 ║ 15.01.2017 ║ 21.01.2017 ║         6.25 ║
║     2 ║ 22.01.2017 ║ 28.01.2017 ║         6.00 ║
╚═══════╩════════════╩════════════╩══════════════╝