Results 1 to 3 of 3

Thread: [RESOLVED] [SQL Server] Aggregates in WHERE clause

  1. #1

    Thread Starter
    Registered User nmadd's Avatar
    Join Date
    Jun 2007
    Location
    U.S.A.
    Posts
    1,676

    Resolved [RESOLVED] [SQL Server] Aggregates in WHERE clause

    SQL Server 9.0.3068

    So, I know I cannot put aggregates in a WHERE clause and this is giving me some trouble with what I think should be a simple query. My goal is to display the sum of sales for items by customer for a certain date range. The date range would be the first sale for the item/customer and all sales up to the following 2 months.

    sql Code:
    1. use SalesData;
    2. go
    3. select
    4.     s.CustomerName,
    5.     s.ItemNumber,
    6.     sum(s.GrossAmount) GrossSales,
    7.     min(s.DocumentDate) MinDocDate,
    8.     dateadd(month, 2, min(s.DocumentDate)) MaxDocDate
    9. from dbo.SalesByItem s
    10. where
    11.     s.ItemNumber = '12345'
    12. group by
    13.     s.CustomerName,
    14.     s.ItemNumber
    15. order by
    16.     s.CustomerName
    I'd love to do something like where s.DocumentDate between MinDocDate and MaxDocDate but I know I can't. I know I can use aggreagates in the HAVING clause but then I'm forced to group by s.DocumentDate which doesn't work as these are individual days and I want to show the sum of sales for the 2 month period.

    Can somebody point this SQL newbie in the right direction?

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: [SQL Server] Aggregates in WHERE clause

    You can use a sub-query to get a calculated value, eg:
    Code:
    AND s.DocumentDate > (
                          SELECT Min(DocumentDate)
                          FROM dbo.SalesByItem
                          WHERE CustomerName = s.CustomerName
                            AND ItemNumber = s.ItemNumber
                          )
    As the main query has an alias for the table, you can refer to it in the sub-query (as I did in the Where clause) to ensure you are mapping to the correct data.

    Use a separate sub-query for each value that you want to calculate, and just put it wherever you would normally put a literal value.
    SQL Server 9.0.3068
    It would be much better to tell us the 'name' of the version (which for 9.x I think is 2005) rather than the full number.

  3. #3

    Thread Starter
    Registered User nmadd's Avatar
    Join Date
    Jun 2007
    Location
    U.S.A.
    Posts
    1,676

    Re: [SQL Server] Aggregates in WHERE clause

    That seemed to do the trick. Thanks!

    And, yes, it is 2005.

Posting Permissions

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



Click Here to Expand Forum to Full Width