我想获得每位员工的总工作时数。数据的详细信息如下:
我想要一周中每位用户的总工作时数。
以上是数据的屏幕截图。 我想在新表中获得每个用户的总工作时数。 我该如何实现?
答案 0 :(得分:2)
因为您只提取了两个值,所以您可以按用户ID(我假设是ClockNo)和日期进行分组,然后使用MIN和MAX函数来拉取开始和结束时间每一天。获得间隔后,您可以按用户总结结果。
SELECT
ClockNo
, MIN( FirstName ) AS FirstName
, MIN( LastName ) AS LastName
, SUM( [Hours] ) AS TotalHours
FROM
(
SELECT
ClockNo
, MIN( FirstName ) AS FirstName
, MIN( LastName ) AS LastName
, [Date]
-- Not sure what the time format is, you'll need to adjust this
, COALESCE( MAX( [Time] ) - MIN( [Time] ), 0 ) AS [Hours]
FROM
ClockTable
GROUP BY
ClockNo, [Date]
) AS HoursPerDay
GROUP BY
ClockNo
答案 1 :(得分:2)
首先要做的是将整数DATE
和TIME
数据转换为可以CONVERT
到DATETIME
或TIME
数据类型的格式,这样您就可以执行DATE函数,如DATEDIFF
,反对
整数DATE
到DATETIME
数据类型
DECLARE @date INT = 20180320
SELECT CONVERT(DATETIME, CAST(@Date AS CHAR(8)), 101)
2018-03-20 00:00:00.000
DECLARE @time INT = 215319
SELECT RIGHT(
CAST(DATEADD(HOUR, (@Time / 1000000) % 100,
DATEADD(MINUTE, (@Time / 10000) % 100,
DATEADD(SECOND, (@Time / 100) % 100, CAST('00:00:00' AS TIME(2)) ) ) )
AS NVARCHAR(16))
, 8)
21:53.00
然后使用派生表LEAD
组合批次DECLARE @t TABLE ( ClockNo INT, FirstName NVARCHAR(50), LastName NVARCHAR(50), [Date] INT, [Time] INT)
INSERT INTO @t(
ClockNo
, FirstName
, LastName
, [Date]
, [Time]
)
SELECT 111, 'J', 'Doe', 20180320, 80620 UNION ALL
SELECT 111, 'J', 'Doe', 20180320, 170124 UNION ALL
SELECT 111, 'J', 'Doe', 20180322, 75436 UNION ALL
SELECT 111, 'J', 'Doe', 20180322, 120854 UNION ALL
SELECT 132, 'S', 'Doe', 20180319, 134630 UNION ALL
SELECT 132, 'S', 'Doe', 20180319, 215319 UNION ALL
SELECT 132, 'S', 'Doe', 20180320, 134630 UNION ALL
SELECT 132, 'S', 'Doe', 20180320, 215319
SELECT X.ClockNo
, X.FirstName
, X.LastName
, TotalHours = CONVERT(VARCHAR, DATEADD(MILLISECOND, SUM(DATEDIFF(SECOND, X.LogOn , X.LogOff)) * 1000, 0), 114)
FROM(
SELECT
T.ClockNo
, T.FirstName
, T.LastName
, T.[Date]
, LogOn = CAST(
CAST(T.[Date] AS CHAR(8)) + ' ' + RIGHT(
CAST(DATEADD(HOUR, (T.[Time] / 1000000) % 100,
DATEADD(MINUTE, (T.[Time] / 10000) % 100,
DATEADD(SECOND, (T.[Time] / 100) % 100, CAST('00:00:00' AS TIME(2)) ) ) )
AS NVARCHAR(16))
, 8)
AS DATETIME)
, LogOff = CAST(LEAD(
CAST(T.[Date] AS CHAR(8)) + ' ' + RIGHT(
CAST(DATEADD(HOUR, (T.[Time] / 1000000) % 100,
DATEADD(MINUTE, (T.[Time] / 10000) % 100,
DATEADD(SECOND, (T.[Time] / 100) % 100, CAST('00:00:00' AS TIME(2)) ) ) )
AS NVARCHAR(16))
, 8)
)
OVER
( PARTITION BY T.ClockNo, T.[Date]
ORDER BY T.[Date], T.[Time]
)
AS DATETIME )
FROM
@t T
) X
GROUP BY
X.ClockNo
, X.FirstName
, X.LastName
返回
ClockNo FirstName LastName TotalHours
111 J Doe 13:09:00:000
132 S Doe 16:14:00:000
警告 - 解决方案仅在LogOn和LogOff在同一天发生时才有效