SQL Server 2014:MAX和HAVING查询

时间:2017-04-13 05:16:26

标签: sql-server

这里有自学成才的新手

我正在尝试在表格EmplUDABreakdown中的最新日期的52周内返回一组值。

DECLARE @AVGEarn TABLE 
   (
     EmployeeCode VARCHAR(12)
     ,AVGEarn DECIMAL(12,2)
     ,Weeks INT
   )

INSERT INTO @AVGEarn
   SELECT 
       E.EmployeeCode,
       (SELECT SUM(EMPL.Amount) 
        FROM EMPLUDABreakdown EMPL 
        WHERE EMPL.EmployeeCode = E.EmployeeCode 
          AND EMPL.UserDefinedAccumulatorCode = 'AVGEARN' 
          AND DATE <= MAX(EMPL.[Date]) 
          AND DATE >= DATEADD(WEEK,-52,MAX(EMPL.[Date]))) AS AVGEarn,
       (SELECT COUNT(DISTINCT EMPL.[Date]) 
        FROM EMPLUDABreakdown EMPL 
        WHERE EMPL.EmployeeCode = E.EmployeeCode 
          AND EMPL.UserDefinedAccumulatorCode = 'AVGHRS' 
          AND DATE <= MAX(EMPL.[Date])  
          AND DATE >= DATEADD(WEEK,-52,MAX(EMPL.[Date])+1)) AS Weeks
   FROM 
       Employee E
   WHERE 
       E.TerminationDate IS NULL
   ORDER BY 
       E.EmployeeCode

   SELECT * FROM @AVGEarn

我收到错误:

  

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

我改为......

   (SELECT SUM(EMPL.Amount) 
    FROM EMPLUDABreakdown EMPL 
    WHERE EMPL.EmployeeCode = E.EmployeeCode 
      AND EMPL.UserDefinedAccumulatorCode = 'AVGEARN' 
    GROUP BY EMPL.[Date]
    HAVING DATE <= MAX(EMPL.[Date]) AND DATE >= DATEADD(WEEK,-52,MAX(EMPL.[Date]))) AS AVGEarn

并收到以下消息

  

Msg 512,Level 16,State 1,Line 8
  子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。

0 个答案:

没有答案