平均值表格列 - mySQL

时间:2016-10-19 08:16:53

标签: mysql

我有这张桌子:

+----+---------+------+----------+
| ID | ID_USER | NOTE | QUESTION |
+----+---------+------+----------+
|  1 |    12   |   3  |     1    |
|  2 |    31   |   2  |     1    |
|  3 |    12   |   9  |     1    |
|  4 |    31   |   8  |     2    |
|  5 |    12   |  10  |     2    |
|  6 |    31   |   3  |     2    |
+----+---------+------+----------+

如何导出值以按ID_USER,QUESTION对其进行分组并制作平均音符?要分组的值如下表所示:

+----+----------+---------+-------------+
| ID | QUESTION | ID_USER | MEDIUM_NOTE |
+----+----------+---------+-------------+
|  1 |     1    |    12   |       6     |
|  2 |     1    |    31   |       2     |
|  3 |     2    |    12   |       10    |
|  4 |     2    |    31   |      5.5    |
+----+----------+---------+-------------+

谢谢!

2 个答案:

答案 0 :(得分:1)

SELECT 
    id_user,
    question,
    AVG(note) AS medium_note
FROM notes 
GROUP BY id_user, question

您可以按用户和问题分组,然后计算平均值。

Example

答案 1 :(得分:0)

假设id列是唯一的:

SELECT id,question,id_user,avg(note) as 'MEDIUM_NOTE' FROM table_name GROUP BY id_user,question ORDER BY id;