DECLARE @Result nvarchar(50)
SET @Result = (select top 1
ROUND(SUM(DATEDIFF(SS,CheckIn,'2014-05-15 03:30:32.507') / 60.0 / 60.0),2)
from CheckInCheckOut
where UserId_Fk=3
order by CheckInCheckOutId desc)
update CheckInCheckOut
set CheckOut='2014-05-15 03:30:32.507',CountHours=@Result
where CheckInCheckOutId = (select top (1) CheckInCheckOutId
from CheckInCheckOut
where UserId_Fk = 3
order by CheckInCheckOutId desc )
当我尝试使用它时,我得到错误:
'Column "CheckInCheckOut.CheckInCheckOutId" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
在这种情况下,如何在select语句中执行group by子句?
答案 0 :(得分:0)
当您在查询中使用聚合函数时,如果使用不在任何聚合函数中的其他属性,则需要在group by
子句中提及它。
在t-sql的开头:
SET @Result = (select top 1 ROUND(SUM(DATEDIFF(SS,CheckIn,'2014-05-15 03:30:32.507') / 60.0 / 60.0),2)
from CheckInCheckOut
where UserId_Fk=3
group by CheckInCheckOutId
order by CheckInCheckOutId desc)
答案 1 :(得分:0)
您可以使用适当的聚合函数来定义最大CheckInCheckOutId:
DECLARE @Result nvarchar(50),@MaxCheckInCheckOutId int
--this value is calculated one time for the whole batch
set @MaxCheckInCheckOutId = (select MAX(CheckInCheckOutId) from CheckInCheckOut where UserId_Fk=3)
set @Result = (select ROUND(SUM(DATEDIFF(SS,CheckIn,'2014-05-15 03:30:32.507') / 60.0 / 60.0),2)
from CheckInCheckOut where UserId_Fk=3 and CheckInCheckOutId=@MaxCheckInCheckOutId)
update CheckInCheckOut
set CheckOut='2014-05-15 03:30:32.507',CountHours=@Result
where CheckInCheckOutId = @MaxCheckInCheckOutId
一些提示: