我试图按项目类型获得用户的平均评级,但包括所有具有评级的用户,而不考虑类型。
SELECT projects.user_id, AVG(ratings.rating) AS avg1
FROM projects
JOIN ratings
ON projects.project_id = ratings.project_id
WHERE projects.type='0'
GROUP BY projects.user_id;
提前感谢您的帮助。
类型0的输出是:
user_id | avg1
-----------------
11 | 2.25
但我正在努力获得:
user_id | avg1
-----------------
11 | 2.25
12 | 0
因为用户12在评级表中有一个项目,但不是类型0,所以我仍然希望它以avg1=0 输出
类型1的输出按预期工作,因为所有具有评级的用户都具有类型1:
user_id | avg1
-----------------
11 | 4
12 | 2.5
项目表为:(评级表中只有前4个项目(
project_id |user_id | type
--------------------------
51 11 0
52 12 1
53 11 0
54 11 1
55 12 1
56 13 0
57 14 1
评级表为:
project_id | rating
-------------------
51 0
51 1
52 4
51 5
52 2
53 3
54 4
52 1.5
使用条件聚合:
SELECT p.user_id,
COALESCE(AVG(CASE WHEN p.type = '0' THEN r.rating END), 0) AS avg1
FROM projects p JOIN ratings r
ON p.project_id = r.project_id
GROUP BY p.user_id;
请参阅演示