简体   繁体   中英

MYSQL Select Average for each distinct entry

I am trying to resolve this problem with a query rather than on the server-side.
I have a table like this:

+----+-----------+--------+--------+
| ID | RateValue | Marker | Marked |
+----+-----------+--------+--------+
|  1 |         8 | USER1  | USER2  |
|  2 |        10 | USER2  | USER1  |
|  3 |         9 | USER3  | USER1  |
|  4 |         8 | USER1  | USER3  |
|  5 |         6 | USER2  | USER3  |
|  6 |         7 | USER3  | USER2  |
+----+-----------+--------+--------+

I want to get a single query that returns me the average for each marked user.

USER1 was marked in row 2 and 3, the total is 9.5 (9+10/2).
USER2 was marked in row 1 and 6, the total is 7.5.

So far, I only managed to get this working by breaking it into two steps: Get all unique marked users:

SELECT DISTINCT Marked FROM reviews

And then get the AVG for each user:

SELECT AVG(rateValue) FROM reviews WHERE Marked = ?

I tried to combine this, but it returns me the total average:

SELECT Marked,AVG(rateValue) FROM reviews WHERE Marked IN (SELECT DISTINCT Marked FROM reviews)

But it returns me the total average, I would like to have a query that returns me the average for each distinct Marked user.

Simply use aggregation:

select marked, avg(ratevalue)
from reviews
group by marked;

If you wanted the average regardless of column, then use union all to unpivot and aggregate:

select user, avg(ratevalue)
from ((select marker as user, ratevalue
       from reviews
      ) union all
      (select marked as user, ratevalue
       from reviews
      )
     ) r
group by user;

This is generic SQL. Some databases have more efficient ways to unpivot two columns.

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