sql select average from distinct column of table
Asked Answered
C

5

8

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

Candelaria answered 15/10, 2014 at 7:53 Comment(1)
Can you share the output you're expecting to get for this data? Your calculation and your text seem to contradict each other.Libidinous
S
8

Try this:

SELECT AVG(T.col2)
FROM 
    (SELECT DISTINCT col1, col2
    FROM yourtable) as T
Streeter answered 15/10, 2014 at 7:59 Comment(0)
S
5

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

select avg(col2)
from (select distinct col1, col2
      from my_table
     ) t
Skuld answered 15/10, 2014 at 7:59 Comment(0)
L
1

Average is the sum of a set of values divided by the number of those value. Here, you want to divide by a count of the distinct values, so:

SELECT SUM(col2)/COUNT (DISTINCT col1)
FROM   my_table
Libidinous answered 15/10, 2014 at 7:54 Comment(2)
Dear, you summarize all valus of col2, not one for distinct col1.Streeter
This is what the OP's text suggests, albeit not his example. Let's ask the OP for clarificationsLibidinous
L
0

You can just say

SELECT col1, AVG( col2 ) FROM my_table GROUP BY col1
Leiker answered 15/10, 2014 at 7:57 Comment(1)
This is wrong, it produces avg for each col1 distinct element separately!Candelaria
N
-1

Try

SELECT AVG(coll2) as Average From myTable Group by Col1,Col2
Notify answered 15/10, 2014 at 7:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.