Convert row-based results to column-based results for different groups of users: How to achieve this "rotation"?
P粉937382230
P粉937382230 2024-03-29 13:22:26
0
1
402

I'm running MySQL 5.7.

I'm looking for a SQL query that "rotates" some data from rows into columns. The form is as follows:

users Table

user_id,first_name
1,Alice
2,Bob
3,Eve
4,Mallory

user_groupsTable

user_id,group_name
1,Administrator
2,Editor
2,Contributor
3,Viewer

Having a limited set of groups, I want to produce the following results:

user_id,first_name,Administrator,Editor,Contributor,Viewer
1,Alice,Yes,No,No,No
2,Bob,No,Yes,Yes,No
3,Eve,No,No,No,Yes
4,Mallory,No,No,No,No

I'm not even sure what I should call this query, but that's what I want to do. "Yes" and "No" can be 0 and 1, or NULL and 1, either way.

Any ideas?

P粉937382230
P粉937382230

reply all(1)
P粉239089443
SELECT u.user_id,
 MAX(CASE group_name WHEN 'Administrator' THEN 'Yes' ELSE 'No' END) AS Administrator,
 MAX(CASE group_name WHEN 'Editor' THEN 'Yes' ELSE 'No' END) AS Editor,
 MAX(CASE group_name WHEN 'Contributor' THEN 'Yes' ELSE 'No' END) AS Contributor,
 MAX(CASE group_name WHEN 'Viewer' THEN 'Yes' ELSE 'No' END) AS Viewer
FROM users AS u
LEFT OUTER JOIN user_groups AS g USING (user_id)
GROUP BY u.user_id;

Unlike some other brands of SQL databases, MySQL does not support any special syntax for PIVOT or CROSSTAB.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template