Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2012
    Posts
    30

    Unanswered: [SQL Server]An aggregate may not appear in the WHERE clause

    Hi all, hope in your help.

    This query not start, why?
    Can you help me?
    Any help would be very appreciated.
    Code:
    [SQL] SELECT
    	DTZZ,
    	[NUM],
    	[ENER],
    	MAX ([MYDATE]) AS max_date
    FROM
    	[dbo].[TBL_49]
    WHERE
    	[ENER] > 0
    AND DTZZ IN ('6M')
    AND YEAR (MAX([MYDATE])) >= YEAR (GETDATE())
    GROUP BY
    	DTZZ,
    	[NUM],
    	[ENER]
    ORDER BY
    	max_date DESC,
    	[ENER] DESC
    
    [Err] 42000 - [SQL Server]An aggregate may not appear in the WHERE clause unless
    it is in a subquery contained in a HAVING clause or a select list, and the column being
    aggregated is an outer reference.

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    Check out the HAVING clause of the SELECT statement. The WHERE clause is evaluated before the GROUP BY takes effect, so it doesn't make sense to use an aggregate function like Max() there because the server doesn't know the Max() value yet. The HAVING clause is executed after the GROUP BY, so you can use Max() in the HAVING clause.

    -PatP
    In theory, theory and practice are identical. In practice, theory and practice are unrelated.

  3. #3
    Join Date
    Aug 2012
    Posts
    30
    Great! thank you very much!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •