这是我上一个问题(Getting an exception with datetime diff)的扩展,但这次我将totalbreaktime
设为float
,以下是我的新查询。
MERGE Time_Tracker as target using (SELECT USERID, cast(DATEDIFF(second,starttime,endtime)/60.0 as numeric(36,2)) as ColumnWithBreaksCount FROM BreaksTable
where CONVERT(Date, StartTime) = CONVERT(Date, GETDATE()) GROUP BY USERID) as source ON target.USERID = source.USERID
WHEN MATCHED THEN UPDATE SET BREAKS = source.ColumnWithBreaksCount;
这次我运行此查询时,我收到以下异常。
Msg 8120, Level 16, State 1, Line 1
Column 'BreaksTable.StartTime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 1
Column 'BreaksTable.EndTime' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
问题:
答案 0 :(得分:3)
您的查询中有此子查询:
SELECT USERID,
cast(DATEDIFF(second, starttime, endtime)/60.0 as numeric(36,2)) as ColumnWithBreaksCount
FROM BreaksTable
WHERE CONVERT(Date, StartTime) = CONVERT(Date, GETDATE())
GROUP BY USERID;
第二列不是聚合列,GROUP BY
子句中表达式中的列也不是。因此错误。
我可以推测你实际上想要第二列的SUM()
:
MERGE Time_Tracker as target using
(SELECT USERID,
cast(SUM(DATEDIFF(second, starttime, endtime)) / 60.0 as numeric(36,2)) as ColumnWithBreaksCount
FROM BreaksTable
WHERE CONVERT(Date, StartTime) = CONVERT(Date, GETDATE())
GROUP BY USERID
) as source
ON target.USERID = source.USERID
WHEN MATCHED THEN UPDATE SET BREAKS = source.ColumnWithBreaksCount;