I have a table that I would like to pivot using cases in Redshift.
CREATE TABLE SurveyResponses (
id int,
question varchar(255),
answer varchar(255)
);
INSERT INTO SurveyResponses (id, question, answer) values (1, 'Dummy question 1', 'responseX');
INSERT INTO SurveyResponses (id, question, answer) values (2, 'Dummy question 1', 'responseY');
INSERT INTO SurveyResponses (id, question, answer) values (3, 'Dummy question 1', 'responseZ');
INSERT INTO SurveyResponses (id, question, answer) values (4, 'Dummy question 2', 'responseA');
INSERT INTO SurveyResponses (id, question, answer) values (5, 'Dummy question 2', 'responseB');
INSERT INTO SurveyResponses (id, question, answer) values (6, 'Dummy question 3', 'responseC');
I tried the following case approach which does not work. I get repeated rows.
Select id,
Case
When question = 'Dummy question 1' then answer Else '' End as question_1,
Case
When question = 'Dummy question 2' then answer Else '' End as question_2,
Case
When question = 'Dummy question 3' then answer Else '' End as question_3
FROM SurveyResponses;
| ID | QUESTION_1 | QUESTION_2 | QUESTION_3 |
|---|---|---|---|
| 1 | responseX | - | - |
| 2 | responseY | - | - |
| 3 | responseZ | - | - |
| 4 | - | responseA | - |
| 5 | - | responseB | - |
| 6 | - | - | responseC |
| 1 | responseX | - | - |
| 2 | responseY | - | - |
| 3 | responseZ | - | - |
| 4 | - | responseA | - |
| 5 | - | responseB | - |
| 6 | - | - | responseC |
| 1 | responseX | - | - |
| 2 | responseY | - | - |
| 3 | responseZ | - | - |
| 4 | - | responseA | - |
| 5 | - | responseB | - |
| 6 | - | - | responseC |
Also, in my real table, I will have 5000+ questions. I would not like to write the case statement for every question. Also, I wanted my column name to be the question text.
Could someone help me in making it Dynamic?