Vlada Katlinskaya
Vlada Katlinskaya

Reputation: 1033

Calculate average using AVG function for multiple numbers

I'm not sure that I used the correct title, I will edit the question if I will understand a little bit more about the topic.

Now I tried to test MySQL's AVG() function and tried the query:

SELECT AVG(1,2,3)

I expected that this will give me 2 as a result. But I've get en error as AVG() intended to receive a column name as single parameter. I can not imagine that I will need this thing anywhere beyond this very artificial example but I believe that I will understand SQL language better if I will be able to execute such queries.

Upvotes: 0

Views: 1182

Answers (2)

Spock
Spock

Reputation: 4900

In you case you could use avg like this

Select avg(data)
From (select 1 as data union 
Select 2 as data union
Select 3 as data) a

There are loads of resources on the Internet for learning sql. You should check some of them out.

Hope that helps.

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269563

Avg() is an aggregation function, so it operates on a single oolumn of values (or a single expression evaluated for each row). It doesn't take multiple arguments. You simply want:

SELECT (1 + 2 + 3) / 3

Contrast this with:

SELECT AVG(t.n)
FROM (SELECT 1 as n UNION ALL
      SELECT 2 UNION ALL
      SELECT 3
     ) t

This summarizes the three rows into one row, calculating the average.

Upvotes: 2

Related Questions