Gopinath Srirangan (11/25/2010)
How do we filter the result using WHERE and HAVING clause as used in group by
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..
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: http://sqlblog.com/blogs/hugo_kornelis