Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase «««1234

Using OVER with an Aggregate Function Expand / Collapse
Posted Thursday, November 25, 2010 7:41 AM



Group: General Forum Members
Last Login: Today @ 8:19 AM
Points: 7,767, Visits: 11,379
Gopinath Srirangan (11/25/2010)
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 MVP
Visit my SQL Server blog:
Post #1026485
Posted Thursday, March 24, 2011 1:09 AM
Say Hey Kid

Say Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey KidSay Hey Kid

Group: General Forum Members
Last Login: Sunday, September 18, 2016 8:42 PM
Points: 665, Visits: 383
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 :)
Post #1083107
Posted Monday, February 27, 2012 9:03 AM
Mr or Mrs. 500

Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500Mr or Mrs. 500

Group: General Forum Members
Last Login: Thursday, December 17, 2015 3:03 PM
Points: 504, Visits: 259
Great question and I have learnt more on 'OVER Clause' that I had not taken used much.

Thank you.
Post #1258327
« Prev Topic | Next Topic »

Add to briefcase «««1234

Permissions Expand / Collapse