0

I have a SQL query that results in a list of students and their advisors. A student can have multiple advisors, but right now there is only one student and one advisor per line, like so:

+---------+---------+
| student | advisor |
+---------+---------+
|       1 | a       |
|       2 | x       |
|       2 | y       |
|       3 | a       |
|       4 | b       |
+---------+---------+

I would like all advisors for a given student to be on one line:

+---------+----------+----------+----------+
| student | advisor1 | advisor2 | advisor3 |
+---------+----------+----------+----------+
|       1 | a        |          |          |
|       2 | x        | y        |          |
|       3 | a        |          |          |
|       4 | b        |          |          |
+---------+----------+----------+----------+

The number of advisor columns is arbitrary at the moment.

SQL Server dynamic PIVOT query? and Write advanced SQL Select are similar questions, but I don't want the advisors' names themselves to be column headings. I'm at a loss as to how to write the PIVOT statement.

My thought process is to loop through each distinct student, then loop through each of that student's advisors and fill in the columns one by one. However, I'm a SQL beginner and I'm not sure how to tackle this.

Community
  • 1
  • 1
SKM
  • 9
  • 1
  • SQL server dynamic pivot query is the answer. Instead of advisor names you can select them as say 'Advisor'+cast(advisorID as varchar(10)) as Advisor. – Cetin Basoz Mar 23 '16 at 20:15
  • do you know that there can only be 3 advisors? – JamieD77 Mar 23 '16 at 20:16
  • @SKM if that duplicate does not help you, you can use this. http://sqlfiddle.com/#!3/5ffbf/1 – JamieD77 Mar 23 '16 at 20:34
  • @JamieD77 Wow, at first glance there's many statements I'm not familiar with yet, but the results look perfect. I have a lot to study and learn! Thank you so much. – SKM Mar 23 '16 at 20:42

0 Answers0