所以我有一个看起来像这样的命令:
SELECT
UserID,
FacilityMMXID,
ScheduleDate,
StartTime,
EndTime
FROM TblPASchedule
WHERE UserID = 244 AND MONTH(ScheduleDate) = 03 AND Year(ScheduleDate) = 2017
输出看起来像这样
UserID FacilityMMXID ScheduleDate StartTime EndTime
----------- ------------- ------------ ---------------- ----------------
244 1 2017-03-17 01:00:00 05:00:00
244 2 2017-03-17 01:00:00 05:00:00
244 3 2017-03-17 01:00:00 05:00:00
244 4 2017-03-17 01:00:00 05:00:00
244 5 2017-03-17 01:00:00 05:00:00
244 6 2017-03-17 01:00:00 05:00:00
244 7 2017-03-17 01:00:00 05:00:00
244 8 2017-03-17 01:00:00 05:00:00
244 9 2017-03-17 01:00:00 05:00:00
244 10 2017-03-17 01:00:00 05:00:00
244 11 2017-03-17 01:00:00 05:00:00
244 12 2017-03-17 01:00:00 05:00:00
244 13 2017-03-17 01:00:00 05:00:00
244 14 2017-03-17 01:00:00 05:00:00
244 15 2017-03-17 01:00:00 05:00:00
244 1 2017-03-17 05:00:00 22:00:00
244 2 2017-03-17 05:00:00 22:00:00
244 3 2017-03-17 05:00:00 22:00:00
244 4 2017-03-17 05:00:00 22:00:00
244 5 2017-03-17 05:00:00 22:00:00
244 6 2017-03-17 05:00:00 22:00:00
244 7 2017-03-17 05:00:00 22:00:00
244 8 2017-03-17 05:00:00 22:00:00
244 9 2017-03-17 05:00:00 22:00:00
244 10 2017-03-17 05:00:00 22:00:00
244 11 2017-03-17 05:00:00 22:00:00
244 12 2017-03-17 05:00:00 22:00:00
244 13 2017-03-17 05:00:00 22:00:00
244 14 2017-03-17 05:00:00 22:00:00
244 15 2017-03-17 05:00:00 22:00:00
我遗漏了ID行,因为在这种情况下它确实不重要。 同样 - 是的 - 我意识到这个表非常多余 - 我不能解决这个问题,因为我不被允许 - 我只能努力让前面提到的求和功能正常工作。
最终目标是配对不同的StartTime和EndTime对,然后找出那些的日期差异 - 然后,在整个月 - 找到所有条目的总和。
据我所知:
使用:
SELECT
UserID,
DATEDIFF(HOUR, StartTime, EndTime) AS 'Hours Worked'
FROM TblPASchedule WHERE UserID = 244 AND MONTH(ScheduleDate) = 03 AND Year(ScheduleDate) = 2017
GROUP BY UserId, StartTime, EndTime
我得到输出:
UserID Hours Worked
----------- ------------
244 4
244 17
但我不太确定我应该从哪里开始。
我最终需要根据UserID对这些总和进行分组,但我认为这是一步一步。我正在使用where子句来处理单个id ...
答案 0 :(得分:1)
此查询获取UserID,Starttime和Endtime
的所有不同集合;WITH CTE AS
(SELECT DISTINCT UserID, StartTime, EndTime FROM [dbo].[TblPASchedule])
SELECT SUM(DATEDIFF(MINUTE, StartTime, EndTime))/60.0 AS 'Hours Worked', UserID
FROM CTE GROUP BY UserID
结果看起来像这样
Hours Worked UserID
1.666666 19
1.233333 37
0.500000 38
答案 1 :(得分:0)
您是否尝试在群组之上包装其他子查询?
SELECT UserId, SUM('Hours Worked') as 'Hours Worked' FROM (
SELECT
UserID,
DATEDIFF(HOUR, StartTime, EndTime) AS 'Hours Worked'
FROM TblPASchedule WHERE UserID = 244 AND MONTH(ScheduleDate) = 03 AND Year(ScheduleDate) = 2017
GROUP BY UserId, StartTime, EndTime
) AS temp
GROUP BY UserId