loading..
Русский    English
15:51

Aggregate function to aggregate function page 1

Let us consider this exercise:

Find the maximum value among the average prices of PCs, counted separately for each manufacturer.


Calculation of average cost for makers is not difficult:

Console
Execute
  1. SELECT AVG(price) avg_price
  2. FROM Product P JOIN PC ON P.model = PC.model
  3. GROUP BY maker;

However, the standard prohibits the use of a subquery as an argument to aggregate function, i.e. we can not solve the exercise by this way:

Console
Execute
  1. SELECT MAX(
  2. SELECT AVG(price) avg_price
  3. FROM Product P JOIN PC ON P.model = PC.model
  4. GROUP BY maker
  5. );

In such cases, use a subquery in the FROM clause:

Console
Execute
  1. SELECT MAX(avg_price)
  2. FROM (SELECT AVG(price) avg_price
  3.       FROM Product P JOIN PC ON P.model = PC.model
  4.       GROUP BY maker
  5.      ) X;

By means of new features of language - window functions - this problem can be solved without a subquery:

Console
Execute
  1. SELECT DISTINCT MAX(AVG(price)) OVER () max_avg_price
  2.       FROM Product P JOIN PC ON P.model = PC.model
  3.      GROUP BY maker;

Note that window functions admit use of aggregate function as argument. DISTINCT keyword is necessary here because the maximal value, which has been counted up over all set of average values, will be "attributed" to each manufacturer.

Bookmark and Share
Pages 1 2 3
The book was updated
several days ago
©SQL-EX,2008 [Evolution] [Feedback] [About] [Links] [Team]
All right reserved.
Rambler's Top100