Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get the average of a count resultset

I have the following SQL:(bitemp)

SELECT COUNT (*) AS Count   FROM Table T  WHERE (T.Update_time =            (SELECT MAX (B.Update_time )               FROM Table B              WHERE (B.Id = T.Id)) GROUP BY T.Grouping 

now I am getting a resultset with a lot of numbers. I want to get the average of this list. At the moment, I am importing the list into excel and use its average function. But there is a AVG function for DB2, but I did not get it to work.

I tried SELECT AVG(COUNT(*)) and also SELECT AVG(*) FROM (theQuery).

like image 821
Xavjer Avatar asked Oct 12 '11 09:10

Xavjer


People also ask

How do you find the average of a count?

How to Calculate Average. The average of a set of numbers is simply the sum of the numbers divided by the total number of values in the set. For example, suppose we want the average of 24 , 55 , 17 , 87 and 100 . Simply find the sum of the numbers: 24 + 55 + 17 + 87 + 100 = 283 and divide by 5 to get 56.6 .

Can you take the average of a count in SQL?

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.

What does count () function returns average value?

COUNT() Syntax The AVG() function returns the average value of a numeric column.

How do I find the average of each row in SQL?

The average is simply calculated by summing the amounts and divide by the difference between min and max dates for each row.


1 Answers

You just can put your query as a subquery:

SELECT avg(count)   FROM      (     SELECT COUNT (*) AS Count       FROM Table T      WHERE T.Update_time =                (SELECT MAX (B.Update_time )                   FROM Table B                  WHERE (B.Id = T.Id))     GROUP BY T.Grouping     ) as counts 

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)   FROM Table T  WHERE T.Update_time =            (SELECT MAX (B.Update_time)               FROM Table B              WHERE (B.Id = T.Id)) 
like image 167
DavidEG Avatar answered Sep 22 '22 09:09

DavidEG