MySQL aggregate functions

We often need to summarize data instead of actually retrieving them, for which MySQL provides special aggregation functions.

function Explanation
AVG() Returns the average of a column
COUNT() Returns the number of rows in a column
MAX() Returns the maximum value of a column
MIN () Returns the minimum value of a column
SUM() Returns the sum of a column

 

1. AVG () function-count the number of rows in the team list and calculate the sum of the values ​​of a specific column to find the average value

The AVG function ignores rows where the column value is NULL

SELECT AVG(age) FROM user

 

2, COUNT () function-determine the number of rows in the table or the number of rows that meet certain conditions

COUNT (*) counts the number of rows in the table, regardless of whether the columns in the table contain null values ​​or NULL

COUNT (colum) counts rows with values ​​in specific columns, ignoring NULL values

SELECT COUNT(*)FROM user

 

3. The MAX () function-returns the maximum value in the column

      MIN () function-returns the minimum value in the column

     They both ignore rows where the column value is NULL

SELECT MAX(age)FROM user
SELECT MIN(age)FROM user

 

4, SUM () function-returns the sum of the specified column value

Ignore rows with column value NULL

SELECT SUM(age)FROM user

 

5. DISTINCT keyword-aggregate different values

For aggregate functions if you only want to calculate rows with different column values, you need to use the keyword DISTINCT, which must specify the column name

As follows, just calculate the average of different ages

SELECT AVG(DISTINCT age)FROM user

 

6. Combined aggregate functions

In fact, the SELECT statement can contain multiple aggregate functions as needed

SELECT  COUNT(age) AS age_count,
        AVG(age) AS age_avg,
        MIN(age) AS age_min,
		MAX(age) AS age_max
		FROM user

Published 138 original articles · praised 34 · 150,000 views

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105511683