Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Aggregate function "AVG()" doesn't support "SELECT TOP 5" qu

Status
Not open for further replies.

fletchsod

Programmer
Dec 16, 2002
181
I'm a bit surprised when I discover this recently... It wasn't made known to me for 8 years til now.

When you do this query...

Code:
SELECT TOP 5 PurchasePrice from tblPurchase 
WHERE Year = '2008' 
AND Make = 'Ford' 
AND Model = 'Mustang'

Instead of 80 rows, I get the 1st 5 rows which works. When you do this average...

Code:
SELECT AVG(PurchasePrice) from tblPurchase 
WHERE Year = '2008' 
AND Make = 'Ford' 
AND Model = 'Mustang'

It average all 80 rows and I got $12,284 (PurchasePrice). But when I do this...

Code:
SELECT TOP 5 AVG(PurchasePrice) from tblPurchase 
WHERE Year = '2008' 
AND Make = 'Ford' 
AND Model = 'Mustang'

I still get $12,284 meaning it used all 80 rows instead of 5 rows.

Why is that? What's wrong with this sql-query?

Thanks...
 
Nothing, just when you use AGGREGATE function the query runs, and after that TOP 5 is executed.
Your query generates just ONE record :).
So use Derived tables:
Code:
SELECT AVG(PurchasePrice) AS Test
FROM (
SELECT TOP 5 PurchasePrice from tblPurchase
WHERE Year  = '2008'
  AND Make  = 'Ford'
  AND Model = 'Mustang'
ORDER BY ?????????????) Tbl1

Borislav Borissov
VFP9 SP2, SQL Server 2000,2005 & 2008.
 
Ah! I assumed from writing this sql-query that that top 5 would run first then AVG() would run second. I guess that's why people say SQL is not smart enough or worse, I'm not smart enough. :)

Thanks...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top