简体   繁体   English

MYSQL Select 每个不同条目的平均值

[英]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). USER1 标记在第 2 行和第 3 行,总数为 9.5 (9+10/2)。
USER2 was marked in row 1 and 6, the total is 7.5. USER2 标记在第 1 行和第 6 行,总数为 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:然后获取每个用户的 AVG:

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:如果您想要平均值而不考虑列,则使用union all来取消透视和聚合:

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.这是通用的 SQL。 Some databases have more efficient ways to unpivot two columns.一些数据库有更有效的方法来反透视两列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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