2016-10-19 58 views
2

我有這個表:平均值形式列 - 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,問題出口值將它們分組,使票據的平均?值分組如下表所示:

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

謝謝!

+1

能否請您嘗試此查詢? SELECT QUESTION,ID_USER,AVG(NOTE)AS MEDIUM_NOTE FROM table_name GROUP BY QUESTION,ID_USER; – vural

+0

工作,謝謝! – ster

回答

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

您可以按用戶和問題分組,然後計算平均值。

Example

+0

工作,謝謝你1 – ster

0

假設id列是獨一無二的:

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