提取分数';s按管理员分组的组的成员和管理员的总和


extract score's sum for members and admin of a group grouped by admin

我有两个表:分数和用户:

user:
--------------
id | name | parent
--------------
1  | jack |0
--------------
2  | John |1
--------------
3  | Jim  |1
--------------
4  | Sara |0
--------------
5  | Ann  |4
--------------
6  | Suzi |4

score:
------------------------
id | title_id | user_id | score
------------------------
1  | 2        |0        |5
------------------------
2  | 4        |1        |4
------------------------
3  | 5        |1        |4
------------------------   

家长是一个小组的管理员,我想提取每个小组的分数总和。现在我有了这个:

select sum(score) from score left join user on user.id=score.user_id where title_id=2 and parent!=0 group by parent_id

但这只返回组成员的和,而不是组的和。还有更好的查询吗?

我认为下面的查询可以满足您的要求。它使用case来区分组长和成员,因此包括所有成员(包括组长):

select (case when u.parent_id = 0 then u.id else u.parent_id end) as grp, sum(s.score)
from user u left join
     score s
     on u.id = s.user_id and s.title_id = 2 
group by (case when u.parent_id = 0 then u.id else u.parent_id end);