2014-09-13 42 views
0

分爲一組管理員和我有2個表:分數和用戶:提取物分數的會員,並通過管理

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 

但這隻返回組成員的總和,而不是組的總和。有沒有更好的查詢?

回答

0

我認爲下面的查詢做你想要的。它使用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);