Skip to content
Advertisement

Transpose table with “list” of the same attributes

Is it possible to transpose a table with repeated columns?

Existing table:

user_id    question_id   body 
1          1             'Text1 1'
1          1             'Text1 1-2'
1          2             'Text1 2'
1          3             'Text1 3'
2          1             'Text2 1'
2          2             'Text2 2'

Cross tab or solution based on

MAX(CASE WHEN r.question_id = 1 THEN r.body ELSE NULL END) AS 'question1'

is not applicable in this scenario because always is match last occurance of repeated attribute.

I want to perform search on the question body but I don’t know how without a transposed table.
E.g. I want to find user_id where question1='...' AND question2='...'

Advertisement

Answer

This is a case of relational division. Two example query techniques to get what you want:

SELECT user_id
FROM   tbl
WHERE  question_id = 1
AND    body = 'Text1 1'

INTERSECT
SELECT user_id
FROM   tbl
WHERE  question_id = 2
AND    body = 'Text1 2';

Or:

SELECT t1.user_id
FROM   tbl t1
JOIN   tbl t2 USING (user_id)
WHERE  t1.question_id = 1
AND    t1.body = 'Text1 1'
AND    t2.question_id = 2
AND    t2.body = 'Text1 2';

-> sqlfiddle demo

Find many more under this related question:
How to filter SQL results in a has-many-through relation

crosstab() from the additional module tablefunc is just a way to display your data in a modified way. But you are looking for a query technique. It’s not a display issue.
You can find many examples for crosstab() here on SO, too, with a search like this one.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement