Sql-Server
T-SQL:如何將 SUM() 與 GROUP BY 一起使用
我有一個非常基本的問題:
我有這個程式碼,它可以工作並返回23 行:
select Issue_ID ,sum(HoursSpent) as TimeSpent --,DateClosed from SixMonthsReview where StaffAssigned = 'Teddy Bear' and DateClosed between '2018-07-01 06:36:26.790' and '2018-08-01 06:36:26.790' group by Issue_ID
但是如果我取消註釋第 4 行,我會收到一個錯誤:
Msg 8120, Level 16, State 1, Line 4 Column 'SixMonthsReview.DateClosed' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
所以我添加
DateClosed
到GROUP BY
但現在返回了40 行,我可以看到雙打。我哪裡錯了?
group by Issue_ID
表示每行Issue_ID
,因此您需要告訴它如何顯示DateClosed
為單個值。也許你想要MAX(DateClosed)
例如?