SQL SERVER – Two Different Requirements for a Single Table Subquery

A subquery can compare rows with an aggregate from the same table. A junior DBA asked about this over lunch.

Individual vessels and a separate grouped tray sit beside distinct reference vessels.

-- Run in WideWorldImporters.
-- Order lines whose individual price exceeds the overall line-price average:
SELECT OrderID, UnitPrice
FROM Sales.OrderLines
WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Sales.OrderLines);
-- The different requirement: orders whose average line price exceeds that average.
SELECT OrderID, AVG(UnitPrice) AS AverageLinePrice
FROM Sales.OrderLines
GROUP BY OrderID
HAVING AVG(UnitPrice) > (SELECT AVG(UnitPrice) FROM Sales.OrderLines);

We discussed this during a performance health check. My original query finds individual order lines above the overall average UnitPrice. An OrderID can appear repeatedly. That query doesn’t calculate each order’s average as the original problem requested.

GROUP BY and HAVING answer the per-order question. Both examples use unweighted line-price averages. A quantity-weighted business requirement needs a different expression. Handle a zero quantity total explicitly.

This subquery is uncorrelated because it has no outer-row reference. Subqueries can also appear in SELECT or FROM under statement-specific rules. The linked follow-up covers correlation.

Related reading

A row above a global average is not an order with a high average, it is a different comparison.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Scripts, SQL Server
Previous Post
SQL SERVER – Cannot Shrink Log File Because Total Number of Logical Log Files
Next Post
SQL SERVER – How to Write Correlated Subquery?

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.