问题
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.
回答1:
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
回答2:
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).
回答3:
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
回答4:
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 |
来源:https://stackoverflow.com/questions/31052969/sql-count-values-higher-than-average-for-a-group