我有以下表格 -
**TimeLogs**
ID
UserID
JobID
TimeTaken
**Jobs**
ID
EstimatedTime
ActualTime
**ClockInLogs**
ID
UserID
ClockDateTimeIn
ClockDateTimeOut
以下查询生成重复记录 -
SELECT tl.JobID, TimeTaken as 'HoursSold',
DATEDIFF(minute, ClockDateTimeIn, ClockDateTimeOut) / 60 as Hours_Difference,
DATEDIFF(second, ClockDateTimeIn, ClockDateTimeOut) / 60 as Minutes_Difference
from TimeLogs tl
INNER JOIN Jobs j on tl.JobID = j.ID
LEFT JOIN ClockInLogs cil on tl.UserID = cil.UserID
where tl.UserID = 10000 and
ClockDateTimeIn BETWEEN DATEADD(wk, DATEDIFF(wk,0,'11/08/2013'), 0) AND
DATEADD(wk, DATEDIFF(wk,0,'11/08/2013'), 6)
group by tl.ID, tl.JobID, j.TotalEstimatedCharge, tl.TimeTaken, cil.ClockDateTimeIn, cil.ClockDateTimeOut
我希望它做的是返回HoursWorked,Hours_Difference和Minutes_Difference之和 - 没有重复。我无法解决重复的来源。有什么想法吗?
由于
答案 0 :(得分:2)
您需要将小时和分钟相加而不是按小组进行分组:
你这样做可能会超过60分钟。
select
tl.JobID,
TimeTaken as 'HoursSold',
Sum(datediff(n, ClockDateTimeIn, ClockDateTimeOut) / 60) Hours_Difference,
Sum(datediff(s, ClockDateTimeIn, ClockDateTimeOut) / 60) Minutes_Difference
from
TimeLogs tl
inner join
Jobs j
on tl.JobID = j.ID
left join
ClockInLogs cil
on tl.UserID = cil.UserID
where
tl.UserID = 10000 and
ClockDateTimeIn between dateadd(wk, datediff(wk,0,'11/08/2013'), 0) and
dateadd(wk, datediff(wk,0,'11/08/2013'), 6)
group by
tl.JobID,
tl.TimeTaken
答案 1 :(得分:0)
在没有看到数据的情况下很难确定,但我怀疑你是按照应该求和的字段进行分组(TimeTaken,ClockDateTimeIn和ClockDateTimeOut):
SELECT tl.JobID,
SUM(TimeTaken) as 'HoursSold',
SUM(DATEDIFF(minute, ClockDateTimeIn, ClockDateTimeOut) / 60) as Hours_Difference,
SUM(DATEDIFF(second, ClockDateTimeIn, ClockDateTimeOut) / 60) as Minutes_Difference
from TimeLogs tl
INNER JOIN Jobs j on tl.JobID = j.ID
LEFT JOIN ClockInLogs cil on tl.UserID = cil.UserID
where tl.UserID = 10000 and
ClockDateTimeIn BETWEEN DATEADD(wk, DATEDIFF(wk,0,'11/08/2013'), 0) AND
DATEADD(wk, DATEDIFF(wk,0,'11/08/2013'), 6)
group by tl.JobID
请注意,我还删除了不在select中的字段的group by,因为这也会创建重复的外观。