Как найти среднее арифметическое 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 Count – How to Select, Sum, and Average Rows in SQL

In SQL, there are two built-in functions to sum or average the data in your table.

In this article I will show you how to use the SUM and AVG functions in SQL using code examples.

How to use the SUM function in SQL

If you need to add a group of numbers in your table you can use the SUM function in SQL.

This is the basic syntax:

SELECT SUM(column_name) FROM table_name;

The SELECT statement in SQL tells the computer to get data from the table.

The FROM clause in SQL specifies which table we want to list.

In this example, we have a table called students with the columns of id, name, date, and total. We want to add up the total number of candy bars sold by all of the students.

Screen-Shot-2021-09-29-at-5.42.26-AM

We can use this syntax to get the total number of candy bars sold:

SELECT SUM(total) FROM students;

The result would be 41.

Screen-Shot-2021-09-29-at-5.44.54-AM

We can also get the sum for each student using the GROUP BY clause.

The first part is to select the name and sum for the total number of candy bars sold, like this:

SELECT name, SUM(total)

The second part is to group the sum by name:

FROM students GROUP BY name;

Here is the complete code to group the total number of candy bars sold by student name.

SELECT name, SUM(total) FROM students GROUP BY name;

This is what the result would look like in our table:

Screen-Shot-2021-09-29-at-5.54.14-AM

Right now the results are grouped alphabetically by student name.

We can modify the code to sort the list of results from largest total to smallest using the ORDER BY clause.

SELECT name, SUM(total) FROM students GROUP BY name ORDER BY total DESC;

The DESC keyword tells the computer to sort from largest to smallest total.

Screen-Shot-2021-09-29-at-6.05.02-AM

If we wanted to sort the total from smallest to largest, then we would omit the DESC keyword.

SELECT name, SUM(total) FROM students GROUP BY name ORDER BY total;

Screen-Shot-2021-09-29-at-6.07.10-AM

How to use the AVG function in SQL

The AVG function finds the arithmetic mean for a group of records in a SQL table. An average, or arithmetic mean, is the sum of a group of numbers divided by the count for that group.

For example, 2+4+4+6+6+8 is 30 divided 6 which results in an average of 5.

This is the basic syntax for the AVG function:

SELECT AVG(column_name) FROM table_name;
   

In this example, we have a table called students, with columns of id , name, date, and scores.  We want to find the average of all the students’ test scores in our table.

Screen-Shot-2021-09-29-at-4.10.47-AM

We have to use this syntax to get the average for the test scores:

SELECT AVG(scores) FROM students; 

The average would be 85.333.

Screen-Shot-2021-09-29-at-4.21.21-AM

We can also use the ROUND function to round our result to the nearest integer.

SELECT ROUND(AVG(scores)) FROM students; 

Screen-Shot-2021-09-29-at-4.32.05-AM

We can also get the average for each student using the GROUP BY clause.

The first part is to select the name and average for the scores, like this:

SELECT name, ROUND(AVG(scores))

The second part is to group the average scores by name:

FROM students GROUP BY name;

This is what the code looks like all together:

SELECT name, ROUND(AVG(scores)) FROM students GROUP BY name;

This is what the result looks like in the table:

Screen-Shot-2021-09-29-at-5.17.28-AM

Conclusion

There may be times were you need to find the sum or average of records in your table.

If you need to add a group of numbers in your table you can use the SUM function in SQL.

This is the basic syntax:

SELECT SUM(column_name) FROM table_name;

If you need to arrange the data into groups, then you can use the GROUP BY clause.

The AVG function finds the arithmetic mean for a group of records in a SQL table. An average, or arithmetic mean, is the sum of a group of numbers divided by the count for that group.

This is the basic syntax.

SELECT AVG(column_name) FROM table_name;

I hope you enjoyed this tutorial and best of luck on your SQL journey.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Ранее в курсе мы научились выбирать все записи из таблицы. Например, мы можем выбрать все записи из таблицы пользователей с помощью такого запроса:

Запрос вернет нам много строк, но точное их количество мы не знаем. Чтобы это выяснить, можно использовать функцию COUNT — она возвращает количество записей в выборке.

Ответить на вопрос «А сколько записей содержится в таблице users?» можно с помощью такого запроса:

SELECT COUNT(*) FROM users;
count

99

Этот запрос выведет нам ровно одно число — количество строк в запросе. Это равносильно количеству пользователей в нашей базе, потому что в этой таблице хранится информация об уникальных пользователях.

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

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

SELECT COUNT(id) FROM users;
count

99

Этот запрос также вернул значение 99 — это количество строк, id которых не равен NULL.

Подадим в качестве аргумента поле email_confirmed:

SELECT COUNT(email_confirmed) FROM users;
count

0

Этот запрос вернул 0, потому что в таблице поле email_confirmed не содержится никаких данных.

Обратите внимание, что COUNT возвращает количество записей в запросе, а не в таблице:

SELECT COUNT(*) FROM users WHERE gender = 'female';
count

56

Этот запрос вернет количество девушек среди всех пользователей.

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 ?

Понравилась статья? Поделить с друзьями:
  • Как найти общий с пожилым человеком
  • Как найти радиус дуги для поворота автомашины
  • Как найти собственные значения для матрицы
  • Как найти отца мартина в административном блоке
  • Гроссмейстерские доспехи школы мантикоры как найти