运行查询时的聚合函数异常

时间:2016-08-29 09:45:25

标签: sql sql-server

这是我上一个问题(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.

问题:

  1. 正如我在上一个问题中所讨论的,我想根据日期将Time_tracker.breaks更新为breakstable.totalbreaktime的总和。
  2. 当我运行查询(前一个)时,它正在考虑所有数据而不是当前日期的数据。
  3. 我的表格数据如下。

    Time_Tracker

    enter image description here

    BreaksTable

    enter image description here

    请让我知道我哪里出错了,我该如何解决这个问题。

    由于

1 个答案:

答案 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;