search

Home  >  Q&A  >  body text

Convert row-based results to column-based results for different groups of users: How to achieve this "rotation"?

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粉937382230P粉937382230272 days ago422

reply all(1)I'll reply

  • P粉239089443

    P粉2390894432024-03-30 00:13:57

    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.

    reply
    0
  • Cancelreply