聚合可能不会出现在WHERE子句中

时间:2014-01-20 10:00:22

标签: sql sql-server

SELECT distinct    t1.EmplID, t3.EmplName
        , t1.RecTime AS InTime
        , t2.RecTime AS [TimeOut]
        , t1.RecDate AS [DateVisited]
        , DATEDIFF(Hour,t1.RecTime, t2.RecTime) TotalHours
FROM  AtdRecord t1 INNER JOIN AtdRecord t2 
ON    t1.EmplID = t2.EmplID 
AND   t1.RecDate = t2.RecDate
AND   t1.RecTime< t2.RecTime
inner join HrEmployee t3 ON t3.EmplID = t1.EmplID 
Order By EmplID, DateVisited 

错误:

  

聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。

实际上我正在尝试检索第一天输入的时间与上一次输入的时间之间的差异(办公室离开和输入时差以计算工作时间)

如果第一个问题解决了,我还希望按EmpName对其进行分组

1 个答案:

答案 0 :(得分:1)

[更新]

简化版

SELECT    t1.EmplID
        , t3.EmplName
        , min(t1.RecTime) AS InTime
        , max(t2.RecTime) AS [TimeOut]
        , DATEDIFF(Hour,min(t1.RecTime),max(t2.RecTime)) TotalHours
        , t1.RecDate AS [DateVisited]
FROM  AtdRecord t1 
INNER JOIN 
      AtdRecord t2 
ON    t1.EmplID = t2.EmplID 
AND   t1.RecDate = t2.RecDate
AND   t1.RecTime < t2.RecTime
inner join 
      HrEmployee t3 
ON    t3.EmplID = t1.EmplID 
group by 
          t1.EmplID
        , t3.EmplName
        , t1.RecDate

[旧]
我认为在获得日期之前你应该先得到最小/最大值并按日期/员工分组:

with times as (
SELECT    t1.EmplID
        , t3.EmplName
        , min(t1.RecTime) AS InTime
        , max(t2.RecTime) AS [TimeOut]
        , t1.RecDate AS [DateVisited]
FROM  AtdRecord t1 
INNER JOIN 
      AtdRecord t2 
ON    t1.EmplID = t2.EmplID 
AND   t1.RecDate = t2.RecDate
AND   t1.RecTime < t2.RecTime
inner join 
      HrEmployee t3 
ON    t3.EmplID = t1.EmplID 
group by 
          t1.EmplID
        , t3.EmplName
        , t1.RecDate
)
SELECT    EmplID
        , EmplName
        , InTime
        , [TimeOut]
        , [DateVisited]
        , DATEDIFF(Hour,InTime, [TimeOut]) TotalHours
from times
Order By EmplID, DateVisited