2016-08-29 73 views
0

這是我以前的問題(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. 當我運行查詢(前一個)時,它正在考慮所有數據而不是當前日期的數據。

而我的表格數據如下。

Time_Tracker

enter image description here

BreaksTable

enter image description here

請讓我知道我要去哪裏錯了,我怎麼能解決這個問題。

感謝

回答

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; 
+0

喜的朋友,這工作真棒,但有小問題,我不能做一個'where'等,其中'CONVERT (Date,BreaksTable.StartTime)= CONVERT(Date,Time_Tracker.Login)',當我運行這個時,這給了我一個例外,因爲'關鍵字'WHERE'附近的語法不正確。 – user3872094