Using OVER with an Aggregate Function

  • Gopinath Srirangan (11/25/2010)


    Hi,

    How do we filter the result using WHERE and HAVING clause as used in group by

    Say like...

    select MAX(TaxRate) AS 'Tax Rate',StateProvinceID

    from Sales.SalesTaxRate where Name <> 'Canadian GST'

    group by StateProvinceID

    having StateProvinceID IN (1,6,7,9)

    order by StateProvinceID

    Thanks for posting this..

    Hi Gopinath,

    In this case, the filter on StateProvinceID can be in either the WHERE or the HAVING, because this is one of the columns in the GROUP BY. I personally prefer to filter as much as possible in the WHERE, so that's where I would move the filter. But in the HAVING is fine as well; just a matter of personal preference.

    The filter on Name must be in the WHERE. The Name is not in the GROUP BY, so tha HAVING cannot filter on Name - after all, the rows in a group can have different names.

    The HAVING clause is mainly used to filter on aggregate. For instance, if you want to see only the states/provinces with a highest tax rate of less than 20%, you would put "MAX(TaxRate) <= 20" in the HAVING clause. Since this refers to an agregate, it cannot be in the WHERE, but must be in the HAVING clause.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

  • Thanks for the great question.

    Window functions are really useful, and can make some complicated queries much simpler.

    However, its one area that I really wish SQL Server would catch up to Oracle and Db2.

    For example, Db2 provides the ability to define a set of rows to apply the aggregate to, with code such as:

    sum(X) over (partition by Y order by Z rows between 1 preceding and current row)

    This would allow the SUM of X to be applied for each group of Y, ordered by Z - but only aggregating the previous row and the current row. Essentially creating a running total, but without CTEs or nested queries.

    Just my 2 cents worth 🙂

  • Great question and I have learnt more on 'OVER Clause' that I had not taken used much.

    Thank you.

Viewing 3 posts - 31 through 33 (of 33 total)

You must be logged in to reply to this topic. Login to reply