我有这张桌子:
+----+---------+----+----+----+
| ID | ID_USER | Q1 | Q2 | Q3 |
+----+---------+----+----+----+
| 1 | 31 | 3 | 4 | 5 |
| 2 | 2 | 5 | 5 | 8 |
| 3 | 5 | 6 | 2 | 3 |
+----+---------+----+----+----+

每个id_user的平均值如何。要有这种类型的表:
+----+---------+-----+
| ID | ID_USER | AVG |
+----+---------+-----+
| 1 | 31 | 4 |
| 2 | 2 | 6 |
| 3 | 5 | 5.5 |
+----+---------+-----+

答案 0 :(得分:2)
简单的答案是:
select id, id_user, (q1 + q2 + q3) / 3 as average
from t;
但是,如果不是所有问题都有值(例如它们是NULL
)并且您想要包含这些值,那么您需要更复杂的逻辑:
select id, id_user,
(coalesce(q1, 0) + coalesce(q2, 0) + coalesce(q3, 0)) /
nullif( (q1 is not null) + (q1 is not null) + (q3 is not null)), 0)
) as average
from t;
答案 1 :(得分:1)
Select id, id_user,
(q1+q2+q3) / 3.0 Avg
From table