I am not sure if this would be called pivoting.
Data in my SQL 2005 table [CustromerRoles] is as such:
CustId RoleId
2 4
2 3
3 4
4 1
4 2
[Roles] table:
RoleId Role
1 Admin
2 Manager
3 Support
4 Assistant
I want to create a view such that:
SELECT * FROM [MYVIEW] will give me the data below:
The 1 & 0's will be bits so that I can display a grid with checkboxes on my UI display.
CustId Admin Manager Support Assistant
2 0 0 1 1
3 0 0 0 1
4 1 1 0 0
So far I have no idea how to go about doing this.
Have you read the documentation on PIVOT in Microsoft SQL Server 2005?
I haven't tested the above, but just based it on the doc. This may get you started.
There doesn't seem to be a way to generate the columns dynamically. You have to hard-code them.
Try this:
Tested. It gives the same result you want.
PIVOT has the disadvantage that the columns must be known, because you have to provide the ids in the query. You can work around this by using dynamic SQL, i.e. generating the PIVOT query dynamically based on separate query results from the Roles table, in your case, then executing the result. This can easily be done in a stored procedure.
Example: