I've got a "Users" table and a "Roles" table with a junction table joining the two, since it's a many-to-many relationship. The Roles are being updated fairly regularly with additions and subtractions as needed. What I would like is a single select statement that lists the UserID and the a simple 0 or 1 indicating whether they are in a given role. Here's an example of what I have:CREATE TABLE [MyUsers]( [UserId] [int] NOT NULL, [UserName] [nvarchar](256) NOT NULL)INSERT INTO [MyUsers] ([UserID],[UserName]) VALUES (1, 'Johnny')INSERT INTO [MyUsers] ([UserID],[UserName]) VALUES (2, 'Sally')INSERT INTO [MyUsers] ([UserID],[UserName]) VALUES (3, 'Mark')INSERT INTO [MyUsers] ([UserID],[UserName]) VALUES (4, 'Rachel')CREATE TABLE [MyRoles]( [RoleId] [int] NOT NULL, [RoleName] [nvarchar](256) NOT NULL)INSERT INTO [MyRoles] ([RoleId],[RoleName]) VALUES (1, 'Training')INSERT INTO [MyRoles] ([RoleId],[RoleName]) VALUES (2, 'Sales')INSERT INTO [MyRoles] ([RoleId],[RoleName]) VALUES (3, 'Service')CREATE TABLE [MyUsersInRoles]( [UserId] [int] NOT NULL, [RoleId] [int] NOT NULL)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (1, 3)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (2, 2)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (3, 1)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (3, 2)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (4, 2)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (4, 3)
What I would like is a select statement that would return the following given the info above:UserName Training Sales Service-------- -------- ----- -------Johnny 0 0 1Sally 0 1 0Mark 1 1 0Rachel 0 1 1
Then, if I were to do the following:INSERT INTO [MyRoles] ([RoleId],[RoleName]) VALUES (4, 'Supervisor')INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (1, 4)INSERT INTO [MyUsersInRoles] ([UserID],[RoleId]) VALUES (2, 4)
It would return this without having to change the original select statement:UserName Training Sales Service Supervisor-------- -------- ----- ------- ----------Johnny 0 0 1 1Sally 0 1 0 1Mark 1 0 0 0Rachel 0 1 1 0
In essence, is there a way to do a crosstab query without knowing in advance the exact number of columns that will be needed, and instead just using the rows from one table as the columns?