简体   繁体   中英

SQL: Count values higher than average for a group

How can one use SQL to count values higher than a group average?

For example:

I have table A with:

q   t
1   5
1   6
1   2
1   8
2   6
2   4
2   3   
2   1

The average for group 1 is 5.25. There are two values higher than 5.25 in the group, 8 and 6; so the count of values that are higher than average for the group is 2.

The average for group 2 is 3.5. There are two values higher than 3.5 in the group, 5 and 6; so the count of values that are higher than average for the group is 2.

Try this :

 select count (*) as countHigher,a.q from yourtable a join 

 (select AVG(t) as AvgT,q from yourtable a group by q) b on a.q=b.q

 where a.t > b.AvgT

 group by a.q

In the subquery you will count average value for both groups, join it on your table, and then you will select count of all values from your table where the value is bigger then average

My answer is very similar to the other answers except the average is calculated with decimal values by adding the multiplication with 1.0 .

This has no negative impact on the values, but does an implicit conversion from integer to a float value so that the comparison is done with 5.25 for the first group, 3.5 for the second group, instead of 5 and 4 respectively.

SELECT count(test.q) GroupCount
    ,test.q Q
FROM test
INNER JOIN (
    SELECT q
        ,avg(t * 1.0) averageValue
    FROM test
    GROUP BY q
    ) result ON test.q = result.q
WHERE test.t > result.averageValue
GROUP BY test.q

Here is a working SQLFiddle of this code .

This query should work on the most common RDBMS systems (SQL Server, Oracle, Postgres).

This should also work:

SELECT t1.name, COUNT(t1.value)
FROM table t1
WHERE t1.value >
  (SELECT AVG(value) FROM table t2
   WHERE t1.name=t2.name)
GROUP BY t1.name

You can use AVG(t) OVER(PARTITION BY) like this. SQL Fiddle

Query

SELECT COUNT(*)OVER(PARTITION BY q) overcount,q,t 
FROM
(
SELECT q,t,AVG(t)OVER(PARTITION BY q) grp_avg FROM o
)C
WHERE t > grp_avg;

Output

| overcount | q | t |
|-----------|---|---|
|         2 | 1 | 6 |
|         2 | 1 | 8 |
|         2 | 2 | 6 |
|         2 | 2 | 4 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM