This might be the follow up question Enum Join answered by @saeedehp. I have one table full of enum value that is joined together to build some user role column in another table.
Example
Table 1 Enum Table
Role - RoleEnumValue
-------------------------
Student - 1
Researcher - 2
Lecturer - 4
Teacher - 8
Table 2 User Table
UserName - Roles
-------------------------
John - 3
Melvin - 14
Result
UserName - UserRoles
--------------------------------
John - Student, Researcher
Melvin - Researcher, Lecturer, Teacher
This is the sql query for getting the result. However i need to write switch case for every rows in Table 1
SELECT t.UserName
, ISNULL(t.C1 + ', ', '') + ISNULL(t.C2, '') + ISNULL(', ' + t.C3, '') +
ISNULL(', ' + t.C3, '') AS [UserRoles]
FROM
(
SELECT UserName,
CASE WHEN (Roles & 1) <> 0 THEN 'Student' END AS C1,
CASE WHEN (Roles & 2) <> 0 THEN 'Researcher' END AS C2,
CASE WHEN (Roles & 4) <> 0 THEN 'Lecturer' END AS C3,
CASE WHEN (Roles & 8) <> 0 THEN 'Teacher' END AS C3
,... -- if i have more rows
FROM "Table 2"
) t
Now the problem is I have table 1 with about 14 to 20 roles and it's not productive to keep adding switch case.
What is the other way to extract out that multiple roles and get the result like above? Can point out which venn diagram this probably fall under?
(I'm using Microsoft SQL Server)
Update
I think the problem i want to solve is to find user role quickly without opening the application to check user one by one.
Great answer by @Gordon Linoff,
Another great answer by @MatBailie, It makes me realize the answer is quite simple.
The solution.
SELECT
u.UserName,
STRING_AGG(r.Role, ',') AS AssignedRoles
FROM "Table 2" u
LEFT JOIN "Table 1" r ON r.RoleEnumValue & u.Roles <> 0
GROUP BY u.UserName