Export (0) Print
Expand All
5 out of 8 rated this helpful - Rate this topic

Correlated Subqueries in a HAVING Clause

A correlated subquery can also be used in the HAVING clause of an outer query. The following example finds the product models for which the maximum list price is more than twice the average for the model.

USE AdventureWorks2008R2;
GO
SELECT p1.ProductModelID
FROM Production.Product p1
GROUP BY p1.ProductModelID
HAVING MAX(p1.ListPrice) >= ALL
(SELECT 2 * AVG(p2.ListPrice)
FROM Production.Product p2
WHERE p1.ProductModelID = p2.ProductModelID) ;
GO

In this case, the subquery is evaluated once for each group defined in the outer query, that is, once for each model of product.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.