Getting summarizing values |
|||||||||||||||||||||||||||||||
How many PC models does a particular supplier produce? How the average price is defined for computers with the same specifications? The answers to these and other questions associated with some statistic information may be obtained by means of summarizing (aggregate) functions. The following aggregate functions are assumed as standard:
All these functions return a single value. In so doing, the functions COUNT, MIN, and MAX are applicable to any data types, while the functions SUM and AVG are only used with numeric data types. The difference between the functions COUNT(*) and COUNT(<column name>) is that the second does not calculate NULL values (as do other aggregate functions). Example 5.5.1 Find out the minimal and maximal prices for PCs: The result is a single row containing the aggregate values:
Example 5.5.2 Find out the number of available computers produced by the maker А:
As a result we get:
Example 5.5.3 If the number of different models produced by the maker A is needed, the query may be written as follows (taking into account the fact that each model in the Product table is shown once):
Example 5.5.4 Find the number of available different PC models produced by maker A. This query is similar to the preceding one for the total number of models produced by maker A. Now we need to find the number of different models in the PC table (available for sale). To use only unique values in calculating the statistic, the parameter DISTINCT with an aggregate function argument may be used. ALL is another (default) parameter and assumes that all the column values returned (besides NULLs) are calculated. The statement
gives the following result:
If we need the number of PC models produced by each maker, we will need to use the GROUP BY clause, placed immediately after the WHERE clause, if any. Suggested exercises: |