Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql select average from distinct column of table

In my table I have some colms like this, (beside another cols)

col1 | col2
s1   |  5
s1   |  5
s2   |  3
s2   |  3
s2   |  3
s3   |  5
s3   |  5
s4   |  7

I want to have average of ALL col2 over Distinct col1. (5+3+5+7)/4=5

like image 216
BlueGirl Avatar asked Oct 15 '14 07:10

BlueGirl


2 Answers

Try this:

SELECT AVG(T.col2)
FROM 
    (SELECT DISTINCT col1, col2
    FROM yourtable) as T
like image 163
Joe Taras Avatar answered Oct 05 '22 00:10

Joe Taras


You are going to need a subquery. Here is one way:

select avg(col2)
from (select distinct col1, col2
      from my_table
     ) t
like image 27
Gordon Linoff Avatar answered Oct 05 '22 00:10

Gordon Linoff