I need expert help. I thought I knew SQL pretty well, at least up to this point. I’m working with SQL Server and need to build a query that lists each registered member and show each of the names of their guest(s) in separate columns instead of rows. Each member could have 0:N guests associated with each member. So, Here are my tables:
Member Table: memberID (PK), FName, LName, …
Guest Table: GuestID (PK), FName, LastName, …
Event Table: GuestID (PK), MemberID (PK),…
I am trying to build a query output like this:
MemberID | Member_FName | Member_LName | Guest1ID | Guest1_Fname | Guest2ID | Guest2_FName …
SAMPLE:
Member Table
MemberID | FName | LName
001 Frank Smith
002 Mary Jane
003 John Henry
Guest Table
GuestID | FName | LName
101 Steve Smith
102 Peter Smith
103 Mike Jane
Event Table
MemberID | GuestID
001 101
001 102
002 103
OUTPUT:
MemberID | FName | LName| GuestID1 | FName1 | LName1 |GuestID2 | FName2 | LName2
001 Frank Smith 101 Steve Smith 102 Peter Smith
002 Mary Jane 103 Mike Jane
003 John Henry
Please let me know if I need to include other information.
thanks in advance!
You can implement both the
UNPIVOTand then thePIVOTfunctions to get the results. TheUNPIVOTtakes your columns and transforms the data into rows and the pivot takes the final result and turns it back into columns:See SQL Fiddle with Demo
The above works great if you know the number of records ahead of time, but if not then you will want to use dynamic sql:
See SQL Fiddle with Demo
Both versions produce the same result: