AVG

The AVG command calculates the average of numerical values in a column.

For Example:

Let's find out the average of salary from employees.

select avg(salary) from employees;

Result:

The average salary in the employees table is approximately 8041.94.

Ecto query for avg

In Ecto, you use the avg/1 function to achieve similar results.

avg/1

Expression example

HR.Employee |> select([c], avg(c.salary)) |> HR.Repo.all()

avg(c.salary) will give the average of column salary from HR.Employee. Here, c is the reference variable that refers to HR.Employee. Refer Aliases in Ecto to know about aliases/reference variables.

Result:

iex(64)> HR.Employee |> select([c], avg(c.salary)) |> HR.Repo.all()
[Decimal.new("8041.9354838709677419")]

Keyword example

HR.Repo.all(from c in HR.Employee, select: avg(c.salary))

select: is a key. c is a value that is a reference variable for HR.Employee.