Как найти среднее значение в таблице sql

In this article, we are going to see how to find the average value in a column in SQL.  A column in the SQL table is the vertical catalog structure. In this article, we will be using the Microsoft SQL Server as our database.

For the purpose of example, we will be creating a sample table and performing the same operations on it.

Table Definition:

We have the following car table in our database :

CREATE TABLE car (
companyid integer ,
companyname varchar(20) ,
totalmodels integer )

The above query creates a car table for us.

Adding Data to Table:

To insert values into the table we need to use the insert statement. Use the below statement to add data to the car table:

INSERT INTO car values(1,'maruti  suzuki',10);
INSERT INTO car values(2,'tata',12);
INSERT INTO car values(3,'volkswagen',8);

The above query will add the data to the car table.

Note: We have to insert values according to the table created. For example, we created a car table with companyid as integer, companyname as varchar, and totalmodels as an integer. So, we need to insert an integer, a character, and an integer else we may get an error.

To verify the contents of the table use the below statement:

SELECT * FROM car;

This will show us our created table as shown below:

Average of all values in a column

For this, we need to use avg() function. We have to pass the column name as a parameter. The avg() function has the following syntax:

SELECT AVG( column_name ) FROM table_name;
  • The avg() function can be used with the SELECT query for retrieving data from a table.

The below query can be used to find the average of the totalmodels column of our cars table:

SELECT AVG(totalmodels) FROM car;

Output :

Let’s verify the output. The average of 10, 12, and 18 is 10.  Hence, we have successfully found out the average of all values n a column of a table.

Finding out the Average without using the AVG() function –

In this approach we will see how we can find out the average value of a column without using the AVG() function. For this purpose we will use two function SUM() and COUNT(). Firstly we will sum all of the values of a certain column and then divide it with the number of elements of that column.

Considering the table is already created and the values are being inserted.

Syntax of SUM()

SELECT SUM(Col_name) FROM Table_Name;

Syntax of COUNT() 

SELECT COUNT(Col_Name) FROM Table_Name;

SQL Code –

SELECT SUM(totalmodels) / COUNT (totalmodels) AS Average FROM car; 

Output – 

Here in this code an alias “Average” has been used to make the output column name “Average”, if the user doesn’t want to use that then they might skip this.

Last Updated :
25 Mar, 2023

Like Article

Save Article

Функция SQL AVG

Функция SQL AVG необходимо в случае, если требуется вычислить среднее значение числового столбца в таблице. Среднее значение функция AVG() в SQL вычисляет среднее значение столбца путем суммирования всех значений записей столбца и деления на количество записей.

AVG SQL Примеры

Рассмотрим пример. Допустим в таблице Price есть столбец Price_unit. В этой таблице содержатся 5 записей. Значения полей столбца Price_unit 3, 5, 14, 38 и 83.

Выполним запрос, возвращающий среднее значение столбца Price_unit

SELECT AVG(Price_unit) AS PriceAvg FROM Price;

Результатом выполнения данного запроса будет

PriceAvg = 28,6

Агрегатные функции

Последнее обновление: 21.05.2018

Агрегатные функции вычисляют некоторые скалярные значения в наборе строк. В MySQL есть следующие агрегатные функции:

  • AVG: вычисляет среднее значение

  • SUM: вычисляет сумму значений

  • MIN: вычисляет наименьшее значение

  • MAX: вычисляет наибольшее значение

  • COUNT: вычисляет количество строк в запросе

Все агрегатные функции принимают в качестве параметра выражение, которое представляет критерий для определения значений. Зачастую, в качестве
выражения выступает название столбца, над значениями которого надо проводить вычисления.

Выражения в функциях AVG и SUM должно представлять числовое значение (например, столбец, который хранит числовые значения).
Выражение в функциях MIN, MAX и COUNT может представлять числовое или строковое значение или дату.

Все агрегатные функции за исключением COUNT(*) игнорируют значения NULL.

Avg

Функция Avg возвращает среднее значение на диапазоне значений столбца таблицы.

Например, пусть есть следующая таблица товаров Products:

CREATE TABLE Products
(
    Id INT AUTO_INCREMENT PRIMARY KEY,
    ProductName VARCHAR(30) NOT NULL,
    Manufacturer VARCHAR(20) NOT NULL,
    ProductCount INT DEFAULT 0,
    Price DECIMAL NOT NULL
);
  
INSERT INTO Products(ProductName, Manufacturer, ProductCount, Price) 
VALUES
('iPhone X', 'Apple', 3, 76000),
('iPhone 8', 'Apple', 2, 51000),
('iPhone 7', 'Apple', 5, 32000),
('Galaxy S9', 'Samsung', 2, 56000),
('Galaxy S8', 'Samsung', 1, 46000),
('Honor 10', 'Huawei', 5, 28000),
('Nokia 8', 'HMD Global', 6, 38000)

Найдем среднюю цену товаров из базы данных:

SELECT AVG(Price) AS Average_Price FROM Products

Для поиска среднего значения в качестве выражения в функцию передается столбец Price. Для получаемого значения устанавливается псевдоним Average_Price, хотя
в принципе устанавливать псевдоним необязательно.

Функция avg и поиск среднего значения в MySQL

На этапе выборки можно применять фильтрацию. Например, найдем среднюю цену для товаров определенного производителя:

SELECT AVG(Price) FROM Products
WHERE Manufacturer='Apple'

Также можно находить среднее значение для более сложных выражений. Например, найдем среднюю сумму всех товаров, учитывая их количество:

SELECT AVG(Price * ProductCount) FROM Products

Count

Функция Count вычисляет количество строк в выборке. Есть две формы этой функции. Первая форма COUNT(*) подсчитывает число строк в выборке:

SELECT COUNT(*) FROM Products

Функция count в MySQL и вычисление количества строк

Вторая форма функции вычисляет количество строк по определенному столбцу, при этом строки со значениями NULL игнорируются:

SELECT COUNT(Manufacturer) FROM Products

Min и Max

Функции Min и Max вычисляют минимальное и максимальное значение по столбцу соответственно.
Например, найдем минимальную цену среди товаров:

SELECT MIN(Price), MAX(Price) FROM Products

MIN и MAX в MySQL

Данные функции также игнорируют значения NULL и не учитывают их при подсчете.

Sum

Функция Sum вычисляет сумму значений столбца. Например, подсчитаем общее количество товаров:

SELECT SUM(ProductCount) FROM Products

Также вместо имени столбца может передаваться вычисляемое выражение. Например, найдем общую стоимость всех имеющихся товаров:

SELECT SUM(ProductCount * Price) FROM Products

All и Distinct

По умолчанию все вышеперечисленных пять функций учитывают все строки выборки для вычисления результата. Но выборка может содержать повторяющие значения.
Если необходимо выполнить вычисления только над уникальными значениями, исключив из набора значений повторяющиеся данные, то для
этого применяется оператор DISTINCT.

SELECT COUNT(DISTINCT Manufacturer) FROM Products

По умолчанию вместо DISTINCT применяется оператор ALL, который выбирает все строки:

SELECT COUNT(ALL Manufacturer) FROM Products

В данном случае мы видим, что производители могут повторяться в таблице, так как некоторые товары могут иметь одних и тех же производителей. Поэтому
чтобы подсчитать количество уникальных производителей, необходимо использовать оператор DISTINCT.

Так как этот оператор неявно подразумевается при отсутствии DISTINCT, то его можно не указывать.

Комбинирование функций

Объединим применение нескольких функций:

SELECT COUNT(*) AS ProdCount,
	   SUM(ProductCount) AS TotalCount,
       MIN(Price) AS MinPrice,
       MAX(Price) AS MaxPrice,
       AVG(Price) AS AvgPrice
FROM Products

Summary: this tutorial, we will show you how to use SQL AVG function to get the average value of a set.

Introduction to SQL AVG function

The SQL AVG function is an aggregate function that calculates the average value of a set. The following illustrates the syntax of the SQL AVG function:

AVG([ALL|DISTINCT] expression)

Code language: SQL (Structured Query Language) (sql)

If we use the ALL keyword, the AVG function takes all values in the calculation. By default, the AVG function uses ALL whether we specify it or not.

If we specify the DISTINCT keyword explicitly, the AVG function will take the unique values only in the calculation.

For example, we have a set of (1,2,3,3,4) and apply the AVG(ALL) to this set, the AVG function will perform the following calculation:

(1+2+3+3+4)/5 = 2.6

Code language: SQL (Structured Query Language) (sql)

However, the AVG(DISTINCT) will process as follows:

(1+2+3+4)/4 = 2.5

Code language: SQL (Structured Query Language) (sql)

SQL AVG function examples

We will use the employees table in the sample database to demonstrate how the SQL AVG function works. The following picture illustrates the structure of the employees table:

employees_table

To calculate the average salary of all employees, you apply the AVG function to the salary column as follows:

SELECT AVG(salary) FROM employees;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG example

Let’s apply the DISTINCT operator to see if the result changes:

SELECT AVG(DISTINCT salary) FROM employees;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG DISTINCT example

It changed because some employees have the same salary.

To round the result to 2 decimal places, you use the ROUND function as follows:

SELECT ROUND(AVG(DISTINCT salary), 2) FROM employees;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG with ROUND function example

To calculate the average value of a subset of values, we add a WHERE clause to the SELECT statement. For instance, to calculate the average salary of employees in the department id 5, we use the following query:

SELECT AVG(DISTINCT salary) FROM employees WHERE department_id = 5;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG WHERE example

The following statement returns the average salary of employees who hold the job id 6:

SELECT AVG(salary) FROM employees WHERE job_id = 6;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG WHERE job id

SQL AVG with GROUP BY clause example

To calculate the average values of groups, we use the AVG function with the GROUP BY clause. For example, the following statement returns the departments and the average salary of employees of each department.

SELECT department_id, AVG(salary) FROM employees GROUP BY department_id;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG GROUP BY example

We can use the inner join clause to join the employees table with the departments table to get the department name data:

SELECT e.department_id, department_name, AVG(salary) FROM employees e INNER JOIN departments d ON d.department_id = e.department_id GROUP BY e.department_id;

Code language: SQL (Structured Query Language) (sql)

Try It

SQL AVG with INNER JOIN example

SQL AVG with ORDER BY clause example

To sort the result set that includes the AVG results, you use the AVG function in the ORDER BY clause as follows:

SELECT
	e.department_id,
	department_name,
	AVG(salary)
FROM
	employees e
INNER JOIN departments d ON d.department_id = e.department_id
GROUP BY
	e.department_id
ORDER BY
	AVG(salary) DESC;

Try It

SQL AVG with ORDER BY example

SQL AVG with HAVING clause example

To filter group, you use the AVG function in the HAVING clause. For example, the following statement gets the department that has the average salary less than 5000:

SQL AVG with HAVING clause example

SQL AVG with a subquery

We can apply AVG function multiple times in a single SQL statement to calculate the average value of a set of average values.

For example, we can use the AVG function to calculate the average salary of employees in each department, and apply the AVG function one more time to calculate the average salary of departments.

The following query illustrates the idea:

SELECT AVG(employee_sal_avg) FROM ( SELECT AVG(salary) employee_sal_avg FROM employees GROUP BY department_id ) t;

Code language: SQL (Structured Query Language) (sql)

Try It

How the query works.

  • The subquery returns a set of the average salaries of employees for each department.
  • The outer query returns the average salary of departments.

In this tutorial, you have learned how to use the SQL AVG function to calculate the average value of a set.

Was this tutorial helpful ?

Summary: in this tutorial, you will learn how to use MySQL AVG() function to calculate the average value of a set of values.

Introduction to MySQL AVG() function

The MySQL AVG() function is an aggregate function that allows you to calculate the average value of a set.

Here is the basic syntax of the AVG() function:

AVG(DISTINCT expression)Code language: SQL (Structured Query Language) (sql)

You use the DISTINCT operator in the AVG function to calculate the average value of the distinct values.

For example, if you have a set of values 1,1,2,3, the AVG function with DISTINCT operator will return 2 i.e., (1 + 2 + 3) / 3.

We will use the products table in the sample database for the demonstration:

products table

A) Using MySQL AVG() function to calculate an average of all values in a column example

This example uses the AVG() function to calculate the average buy price of all products from the products table:

SELECT 
    AVG(buyprice) 'Average Price'
FROM
    products;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - average product price

B) Using MySQL AVG() function with a WHERE clause example

The following  example uses the AVG() function to calculate the average buy price of products in the product line Classic Cars:

SELECT 
    AVG(buyprice) 'Average Classic Cars Price'
FROM
    products
WHERE
    productline = 'Classic Cars';Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - Average Classic Cars Price

In this example, the WHERE clause has a condition that includes only the Classic Cars product line. Therefore, the AVG() function calculates the average value for the buy prices of products in Classic Cars only.

C) Using MySQL AVG with DISTINCT option example

This query checks if there are any products which have the same prices:

SELECT 
    COUNT(buyprice) - COUNT(DISTINCT buyprice)
FROM
    products;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - COUNT function

This query uses the AVG() function with the DISTINCT option to calculate the average of distinct buy prices:

SELECT 
    FORMAT(AVG(DISTINCT buyprice), 2)
FROM
    products;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - average distinct product prices

Notice that the result is different from the average buy price without using the DISTINCT operator.

D) MySQL AVG with GROUP BY clause example

The AVG() function is often used in conjunction with the GROUP BY clause to calculate the average value for each group of rows in a table.

For example, to calculate the average buy price of products for each product line, you use the AVG() function with the GROUP BY clause as the following query:

SELECT 
    productline, 
    AVG(buyprice) 'Average Price'
FROM
    products
GROUP BY productline;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - average buy price by product line

E) Using MySQL AVG() function with a HAVING clause example

You can use the AVG() function in the HAVING clause to set conditions for the average values of groups.

For example, if you want to select only product lines that have the product’s average buy prices greater than 50, you can use the following query:

SELECT 
    productline, 
    AVG(buyprice) 'Average Price'
FROM
    products
GROUP BY productline
HAVING AVG(buyprice) > 50;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - with GROUP BY clause

F) Using MySQL AVG() function with a subquery example

You can use the AVG() function in an SQL statement multiple times to calculate the average value of a set of average values.

This query uses the AVG() function to calculate the average buy price of the average buy prices of product lines:

SELECT 
    AVG(pl_avg) 'Average Product'
FROM
    (SELECT 
        AVG(buyprice) pl_avg
    FROM
        products
    GROUP BY productline) avgs;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - with subquery example

How it works.

  • The subquery calculates the average buy price by product lines.
  • The outer query calculates the average buy price of the average buy prices of product lines returned from the subquery.

G) Using MySQL AVG() function with NULL example

The AVG() function ignores NULL values in the calculation. See the following example:

First, create a new table named t with two columns id and val. The val column can contain NULL values.

CREATE TABLE IF NOT EXISTS t (
    id INT AUTO_INCREMENT PRIMARY KEY,
    val INT
);Code language: SQL (Structured Query Language) (sql)

Second, insert some rows into the t table, including NULL value.

INSERT INTO t(val)
VALUES(1),(2),(nulL),(3);Code language: SQL (Structured Query Language) (sql)

Third, calculate the average value of the values in the val column by using the AVG function:

SELECT 
    AVG(val)
FROM
    t;Code language: SQL (Structured Query Language) (sql)

MySQL AVG function - NULL example

The statement returns 2 as expected because the NULL value is not included in the calculation of the AVG function.

H) Using MySQL AVG() function with control flow functions

To calculate the average value of a column and calculate the average value of the same column conditionally in a single statement, you use AVG() function with control flow functions e.g., IF, CASE, IFNULL, and NULLIF.

For example, to calculate the ratio of the average buy price of Classic Cars product line to average buy price of all products, you use the following statement:

SELECT 
    AVG(IF(productline = 'Classic Cars',
        buyprice,
        NULL)) / AVG(buyprice) 'Classic Cars/ Products'
FROM
    products;Code language: SQL (Structured Query Language) (sql)

Try It Out

MySQL AVG function - with control flow function

The IF(productline='Classic Cars',buyprice,NULL) expression returns the buy price if the product line is Classic Cars, otherwise NULL.

Because the AVG() function ignores the NULL values in the calculation so the AVG(IF(productline='Classic Cars',buyprice,NULL)) expression returns the average buy price for only products whose product line is Classic Cars.

In this tutorial, you have learned some useful techniques to calculate the average value of a set of values by using theAVG() function.

Was this tutorial helpful?

Понравилась статья? Поделить с друзьями:
  • Как найти номер счета банка втб
  • Как найти пятую свинью
  • Как найти определяемое слово в деепричастном обороте
  • Как найти транзакции на sap
  • Как найти флаг в картинке