I am trying to join three tables in SQL Server 2008 R2, where I want the items in the second table to be added as new column.
To explain in detail – I have 3 tables:
First table contains User Name and User ID
UserID UserName
1 Mike
2 John
3 George
Second Table is position ID’s with Position Names
PositionID PositionName
1 RW
2 LW
3 DF
4 MDF
5 SS
6 CF
etc
Third table table contains their preferred positions where one user can have more than one
UserID PositionId
1 1
1 3
2 2
2 3
2 5
3 2
3 7
When I join these tables I want to get single row for every user with all the preferred positions like
UserID UserName PreferedPosition PreferedPosition2 PreferedPosition3
1 Mike RW LW
2 John CMF SS CF
3 George LW MDF
I don’t know how to achieve this, any help would be appreciated.
If you have only a few numbers of positions, you can do it with
PIVOTkeywordSQL FIDDLE
If, however, you want to have a dynamic number of columns, you have to use dynamic SQL, like this
SQL FIDDLE