[MySQL] Summary Data - avg (), count (), max (), min (), sum () function is used

Chapter 12 summarizes data

What is the learning SQL aggregate functions and how to use their data summary table .

Simple record - MySQL must know will be - [English] Ben Forta

Aggregate functions summarize data

1, aggregate functions

We often need to aggregate data without them actually retrieved, aims to provide a special function MySQL. Using these functions, MySQL query can be used to retrieve the data, for analysis and report generation. Actually want is to aggregate information

To facilitate this type of retrieval, MySQL gives five aggregate functions, as shown below. These functions can be summarized information.

SQL aggregate functions

函数   				说明
AVG()				返回某列的平均值
COUNT()				返回某列的行数
MAX()				返回某列的最大值
MIN()				返回某列的最小
SUM()				返回某列之和 

avg()、count()、max()、min()、sum()

Aggregate functions (aggregate function):

Groups on the line running, calculation function and return a single value.

Below is an explanation of each function.

1.1, AVG () function AVG ()

The AVG () by counting the number of rows of the table and calculates the sum of a particular column, to obtain the average value of the column .

The AVG () is used to return the average of all the columns may be used to return the average value of a particular column or row. And a particular column value / average value was determined counts the number of rows of the column =

AVG()

The following example uses AVG () returns the products table average price of all products:

mysql> SELECT AVG(prod_price) AS avg_price FROM products;
+-----------+
| avg_price |
+-----------+
| 16.133571 |
+-----------+
1 row in set (0.01 sec)

mysql>

AVG(prod_price) AS avg_price avg_price is an alias.

The AVG () can also be used to determine the average value of a particular column or row . (Not just the average of all rows of a column), plus a filter condition.

The following example returns a specific vendor to provide an average price of products:

mysql> SELECT AVG(prod_price) AS avg_price FROM products WHERE vend_id = 1003;
+-----------+
| avg_price |
+-----------+
| 13.212857 |
+-----------+
1 row in set (0.00 sec)

mysql> SELECT vend_id,prod_price FROM products WHERE vend_id = 1003;
+---------+------------+
| vend_id | prod_price |
+---------+------------+
|    1003 |      13.00 |
|    1003 |      10.00 |
|    1003 |       2.50 |
|    1003 |      50.00 |
|    1003 |       4.49 |
|    1003 |       2.50 |
|    1003 |      10.00 |
+---------+------------+
7 rows in set (0.00 sec)

mysql>

More than a WHERE clause. This WHERE clause filters only vend_id 1003 product, thus returned avg_price only an average value of the vendor's products.

The AVG () is used only for a single column, it can only be used to determine the average value of a particular column, and the column name must be given as a function parameter. In order to obtain an average value of a plurality of columns, you must use a plurality of the AVG () function.avg(列名),avg(列名)...

Note: NULL value the AVG () functions ignore row column value is NULL . It does not count.

1.2, COUNT () function count ()

COUNT () function is counted. Available COUNT () to determine the number of rows in the table or rows that meet specific criteria. COUNT () function used in two ways.

  • Use COUNT ( *) for counting the number of rows in a table, regardless of the table column contains a null value (NULL) or non-null value. (COUNT *number) all rows of statistics
  • Use COUNT (column) having a row of a particular column value counts NULL value is ignored. COUNT () ignore NULL technology

The following example returns the total number of client customers table:

mysql> SELECT COUNT(*) AS num_cust FROM customers;
+----------+
| num_cust |
+----------+
|        5 |
+----------+
1 row in set (0.00 sec)

mysql> SELECT * FROM customers;
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
| cust_id | cust_name      | cust_address        | cust_city | cust_state | cust_zip | cust_country | cust_contact | cust_email          |
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
|   10001 | Coyote Inc.    | 200 Maple Lane      | Detroit   | MI         | 44444    | USA          | Y Lee        | [email protected]     |
|   10002 | Mouse House    | 333 Fromage Lane    | Columbus  | OH         | 43333    | USA          | Jerry Mouse  | NULL                |
|   10003 | Wascals        | 1 Sunny Place       | Muncie    | IN         | 42222    | USA          | Jim Jones    | [email protected] |
|   10004 | Yosemite Place | 829 Riverside Drive | Phoenix   | AZ         | 88888    | USA          | Y Sam        | [email protected]    |
|   10005 | E Fudd         | 4545 53rd Street    | Chicago   | IL         | 54545    | USA          | E Fudd       | NULL                |
+---------+----------------+---------------------+-----------+------------+----------+--------------+--------------+---------------------+
5 rows in set (0.00 sec)

mysql>

SELECT COUNT(*) AS num_cust FROM customers;Using COUNT (*) counts all rows, regardless of what row of each column value, the count value is returned in num_cust.

The following example is only for customers with an email address count:

mysql> SELECT COUNT(cust_email) AS num_cust FROM customers;
+----------+
| num_cust |
+----------+
|        3 |
+----------+
1 row in set (0.00 sec)

mysql>

This SELECT statement using Analysis COUNT(cust_email)of cust_emailthe column with a row value is counted. In this example, the count of the CUST_EMAIL 3 (showing only three five clients customers have an email address, an email address 2 is no).

Note: NULL value if the column name specified, the specified row is empty column is COUNT () function is ignored, but if COUNT () is a function with an asterisk (*), is not negligible.

1.3, MAX () function max ()

MAX () returns the largest value in the specified column. MAX () requires column names are specified as follows:

mysql> SELECT MAX(prod_price) AS max_price FROM products;
+-----------+
| max_price |
+-----------+
|     55.00 |
+-----------+
1 row in set (0.01 sec)

mysql> SELECT prod_price FROM products;
+------------+
| prod_price |
+------------+
|       5.99 |
|       9.99 |
|      14.99 |
|      13.00 |
|      10.00 |
|       2.50 |
|       3.42 |
|      35.00 |
|      55.00 |
|       8.99 |
|      50.00 |
|       4.49 |
|       2.50 |
|      10.00 |
+------------+
14 rows in set (0.00 sec)

mysql>

Here, MAX () returns the list price of products in the most expensive items. SELECT MAX(prod_price) AS max_price FROMThe highest price items.

Note: the use of non-numerical data MAX ()

Although MAX () is generally used to find the maximum value or date value, but allows it to MySQL returns the maximum value in any column, including the text column returns the maximum value. When text data, if the data is sorted according to the corresponding column, the MAX () Returns the last row.

mysql> SELECT MAX(prod_name) FROM products;
+----------------+
| MAX(prod_name) |
+----------------+
| TNT (5 sticks) |
+----------------+
1 row in set (0.00 sec)

mysql> SELECT prod_name FROM products;
+----------------+
| prod_name      |
+----------------+
| .5 ton anvil   |
| 1 ton anvil    |
| 2 ton anvil    |
| Detonator      |
| Bird seed      |
| Carrots        |
| Fuses          |
| JetPack 1000   |
| JetPack 2000   |
| Oil can        |
| Safe           |
| Sling          |
| TNT (1 stick)  |
| TNT (5 sticks) |
+----------------+
14 rows in set (0.00 sec)

mysql>

Indeed max () Returns a string parameter is the last one.

NULL value MAX () functions ignore row column value is NULL.

1.4, MIN () function min ()

MIN () function exactly () opposite to the MAX function that returns the minimum value specified column. As with the MAX (), MIN () required to specify the column name, as shown in the following example:

mysql> SELECT prod_price FROM products;
+------------+
| prod_price |
+------------+
|       5.99 |
|       9.99 |
|      14.99 |
|      13.00 |
|      10.00 |
|       2.50 |
|       3.42 |
|      35.00 |
|      55.00 |
|       8.99 |
|      50.00 |
|       4.49 |
|       2.50 |
|      10.00 |
+------------+
14 rows in set (0.00 sec)

mysql> SELECT MIN(prod_price) AS min_price FROM products;
+-----------+
| min_price |
+-----------+
|      2.50 |
+-----------+
1 row in set (0.00 sec)

mysql>

Where MIN () returns the products table cheapest items.

Use MIN () MIN () function for non-numerical data similar to the MAX () function, MySQL allowing it to return to the minimum value in any column, including the text column returns the minimum value. When text data, if the data is sorted according to the corresponding column, the MIN () Returns the top row.

Examples are as follows:

mysql> SELECT min(prod_name) FROM products;
+----------------+
| min(prod_name) |
+----------------+
| .5 ton anvil   |
+----------------+
1 row in set (0.00 sec)

mysql> SELECT prod_name FROM products;
+----------------+
| prod_name      |
+----------------+
| .5 ton anvil   |
| 1 ton anvil    |
| 2 ton anvil    |
| Detonator      |
| Bird seed      |
| Carrots        |
| Fuses          |
| JetPack 1000   |
| JetPack 2000   |
| Oil can        |
| Safe           |
| Sling          |
| TNT (1 stick)  |
| TNT (5 sticks) |
+----------------+
14 rows in set (0.00 sec)

mysql>

NULL value MIN () functions ignore row column value is NULL.

1.5, SUM () function sum ()

The SUM () is used to return the value of the specified column and the (total) .

Here is an example, OrderItems order table contains the actual items, each item has a corresponding number (quantity). Total (all values ​​and quantity) may retrieve items ordered as follows:

mysql> SELECT SUM(quantity) AS items_ordered FROM orderitems WHERE order_num = 20005;
+---------------+
| items_ordered |
+---------------+
|            19 |
+---------------+
1 row in set (0.00 sec)

mysql>

SELECT SUM(quantity) AS items_ordered FROM orderitems WHERE order_num = 20005;Function SUM (quantity) returns the number of orders for all items and, WHERE clause to ensure that the statistics only an item order items.

The SUM () can also be used to calculate the total value. In the following example, the total of each item item_price*quantity, to obtain the total order amount:

mysql> SELECT SUM(item_price*quantity) AS total_price FROM orderitems WHERE order_num = 20005;
+-------------+
| total_price |
+-------------+
|      149.87 |
+-------------+
1 row in set (0.00 sec)

mysql>

SELECT SUM(item_price*quantity) AS total_price FROM orderitems WHERE order_num = 20005;Function SUM (item_price * quantity) in order to return the sum of all goods prices, WHERE clause to ensure that the same statistics only an item order items.

Calculated on a plurality of columns

As shown in this example, using standard arithmetic operators, aggregate functions can all be used to perform calculations on a plurality of columns.- + * /

NULL value the SUM () function ignores row column value is NULL.

2, different values ​​aggregation

DISTINCT aggregate function is used. distinct

5 or more aggregate functions can be used as follows:

  • Perform calculations for all rows, specify ALL parameter or parameters not to (because ALL is the default behavior);
  • Contains only different values, specify DISTINCT parameters.

ALL is the default

ALL parameter need not be specified, because it is the default behavior. If you do not specify DISTINCT, it is assumed to ALL.

The following example uses the AVG () function returns the average price of a particular vendor's products. It is the same with the SELECT statement above, but using DISTINCT parameters, so only consider the average of the different prices (remove duplicate):

mysql> SELECT AVG(DISTINCT prod_price) AS avg_price FROM products WHERE vend_id = 1003;
+-----------+
| avg_price |
+-----------+
| 15.998000 |
+-----------+
1 row in set (0.01 sec)

mysql>

Can be seen that, SELECT AVG(DISTINCT prod_price) AS avg_price FROM products WHERE vend_id = 1003;after using DISTINCT, avg_price this example is relatively high, because there are a plurality of articles having the same low price. They ruled out lifting the average price.

note

If you specify a column name can only be used DISTINCT COUNT ().

DISTINCT can not be used COUNT (*), and therefore does not allow COUNT (DISTINCT), or an error.

mysql> SELECT COUNT(DISTINCT prod_price)  FROM products WHERE vend_id = 1003;
+----------------------------+
| COUNT(DISTINCT prod_price) |
+----------------------------+
|                          5 |
+----------------------------+
1 row in set (0.01 sec)

mysql> SELECT prod_price  FROM products WHERE vend_id = 1003;
+------------+
| prod_price |
+------------+
|      13.00 |
|      10.00 |
|       2.50 |
|      50.00 |
|       4.49 |
|       2.50 |
|      10.00 |
+------------+
7 rows in set (0.00 sec)

mysql> SELECT COUNT(prod_price)  FROM products WHERE vend_id = 1003;
+-------------------+
| COUNT(prod_price) |
+-------------------+
|                 7 |
+-------------------+
1 row in set (0.00 sec)

mysql> SELECT COUNT(DISTINCT )  FROM products WHERE vend_id = 1003;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')  FROM products WHERE vend_id = 1003' at line 1
mysql>

Similarly, DISTINCT column name must be used, or not used to calculate expressions.

The DISTINCT for MIN () and MAX () and MAX Although technically DISTINCT can be used for MIN () (), but this is actually worthless. Minimum and maximum values regardless of whether a column containing a different value is the same.

remove duplicate distinct values.

3, a combination of aggregate functions

Examples of aggregate functions all so far involve only a single function. But in fact SELECT statement can contain multiple aggregate functions as needed. Consider the following example: number of items in the table statistical products, the lowest product prices, as well as the highest average value

mysql> SELECT COUNT(*) AS num_items,MIN(prod_price) AS price_min,MAX(prod_price) AS price_max,AVG(prod_price) AS price_avg FROM products;
+-----------+-----------+-----------+-----------+
| num_items | price_min | price_max | price_avg |
+-----------+-----------+-----------+-----------+
|        14 |      2.50 |     55.00 | 16.133571 |
+-----------+-----------+-----------+-----------+
1 row in set (0.00 sec)

mysql>

MIN(prod_price) AS price_min

... AS 别名Alias ​​when specifying an alias to include the results of aggregate functions should not be used in the actual table column names. While this is not illegal, but using only the name will make your SQL easier to understand and use (easy troubleshooting, and future).

4. Summary

Aggregate functions to summarize data. MySQL supports a number of aggregate functions, you can use several ways to use the results they need to return. These functions are efficiently designed, they return the result of the calculation in general than their own client applications much faster. After all, MySQL is a database management system for data processing.

The AVG () is used to return the average of all the columns may be used to return the average value of a particular column or row.

COUNT () function is counted. Available COUNT () to determine the number of rows in the table or rows that meet specific criteria. COUNT () function used in two ways.

  • Use COUNT ( *) for counting the number of rows in a table, regardless of the table column contains a null value (NULL) or non-null value. (COUNT *number) all rows of statistics
  • Use COUNT (column) having a row of a particular column value counts NULL value is ignored. COUNT () Technical ignore NULL.

MAX () returns the largest value in the specified column. MAX () requires you to specify the column name.

MIN () function exactly () opposite to the MAX function that returns the minimum value specified column. And MAX () the same, MIN () requires you to specify the column name.

The SUM () is used to return the value of the specified column and the (total) .

DISTINCT aggregate function is used. distinct

5 or more aggregate functions can be used as follows:

  • Perform calculations for all rows, specify ALL parameter or parameters not to (because ALL is the default behavior);
  • Contains only different values, specify DISTINCT parameters.

remove duplicate distinct values.

Function uses a combination of aggregate.

Published 88 original articles · won praise 12 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41569732/article/details/104483488