I've been looking through StackOverflow questions and haven't really found one for this issue.
I have a table that's arranged basically like:
Table.LineID
Table.QuestionGroup
Table.Question
Table.Answer
And I'd like to "pivot" the table, but the questions and answers don't have anything to aggregate. They're all just text fields for example, one might read:
Table.LineID = 00001
Table.QuestionGroup = Color
Table.Question = Outside Color
Table.Answer = Dark Green
Table.LineID = 00001
Table.QuestionGroup = Size
Table.Question = Height
Table.Answer = 180 3/4
I'm trying to pivot the table so that I can get the associated ID of line and make that the spreading function the Questions So it would look like
LineID | Question 1 | Question 2 | Etc...
| Answer 1 | Answer 2 | Etc...I've looked at this https://stackoverflow.com/a/7744347/839330 except this seems to be more in reference to some VB code (maybe I'm wrong?). Does anyone have an idea on how I should approach this?
Just because you have text data in your table does not mean that you cannot use an aggregate function on it.
You did not specify what RDBMS you are using but this type of data transformation is a pivot. This converts row data into columns. Some databases has a pivot function but if you are using one without that function, then you will need to use an aggregate function with a
CASE
expression:See SQL Fiddle with Demo
If you have a database that has the pivot function (SQL Server 2005+/Oracle 11g+), then your code will be similar to this:
See SQL Fiddle with Demo
Now if you are using SQL Server 2005+ and you have an unknown number of questions that you want to turn into columns, then you can use dynamic sql similar to this:
See SQL Fiddle with demo
Based on your sample data the result is: