如何在select语句中使用Group by子句

时间:2014-05-15 10:13:22

标签: sql-server group-by sql-update sql-order-by

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子句?

2 个答案:

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

一些提示:

  1. 你也没有提到你的SQL Server版本,也许在高于2000的服务器中使用CTE(通用表表达式)会更好。
  2. 这里你可以面对参数嗅探,所以"选项(重新编译)"或者像这样需要更好的表现。