查询,根据mysql中每个项目的角色来隔离用户



我有一个表,其中包含projectID、UserID和RoleID以及其他列。

我试图获得一个查询,该查询将根据每个项目的角色为我提供用户。

我尝试了if和case语句,但能够解决这个问题。

表:

projectid   | userid | roleid | flag 
1000001     | 20001  | 1      | Y    
1000001     | 20002  | 2      | Y    
1000001     | 20003  | 2      | Y   
1000001     | 20004  | 3      | Y    
1000001     | 20005  | 1      | Y   
1000002     | 20006  | 3      | Y   

考虑角色1=初级,2=TL,3=HOD,我正试图获得这样的

projectid | junior       | TL           | HOD 
1000001   | 20001, 20005 | 20002, 20003 | 20004
1000002   | -------------| -------------| 20006

您需要使用group_concat

select projectid,
group_concat(case when roleid = 1 then userid end) junior,
group_concat(case when roleid = 2 then userid end) senior,
group_concat(case when roleid = 3 then userid end) TL
from table1
group by projectid

小提琴

最新更新