I’m having a really hard time finding any examples that are close to what I’m doing, or I’m simply not understanding the examples I’m finding.
I have a research database that contains a persons responses to multiple questions at different points in time. ‘Admin#’ below represents which “administration” of the test the data represents. Or you can think of it as containing which ‘time’ the test was given, for example, time1, time2, time3
RespondentID# Admin# Question1 Question2 Question3 Question4 Question5
1 1 A B C D E
1 2 E D C B A
1 3 Q W E R T
2 1 Z X C V B
2 2 P O I U Y
2 3 Y H N U J
What I need to do now is arrange this data so that each set of responses for a particular respondent is in the same row. So we’d take the 5 question fields and turn them into 15 question fields,
RespondentID# Admin1Question1 Admin1Question2 Admin1Question3 Admin1Question4 Admin1Question5 Admin2Question1 Admin2Question2 Admin2Question3 Admin2Question4 Admin2Question5 Admin3Question1 Admin3Question2 Admin3Question3 Admin3Question4 Admin3Question5
As you can see, every field that begins with Admin1 would correspond to the row in the example above that has a Admin# value of 1.
Please forgive me if I’m not explaining this properly.
To further complicate matters, the maximum number of “administrations” or “times” can increase in the future. Currently it is 3, but it is possible that the same test could be administered 4, 5 or more times in the future. Whatever solution used for this problem can be static and then updated by hand to account for additional “times” in the future, but it would be awesome if the solution dynamically accounted for an unspecified number of “times”.
This data is stored in a MS SQL 2005 database, so tsql is obviously an option, but if a better solution exists in C# or LINQ (the overall project is an asp.net app), I’m open to that as well. Whatever you think works best! 🙂
Thanks so much for reading my question!
The basic approach I’m following is to manually pivot using code like:
So, using a dynamic t-sql statement we build and execute the query for this as follows:
It’s not the most dynamic t-sql solution available, but it should work!