Consider the following demo:
CREATE TEMP TABLE qa (id int, usr int, question_id int, answer_id int); INSERT INTO qa VALUES (1,1,1,1) ,(2,1,2,9) ,(3,1,3,15) ,(4,2,1,2) ,(5,2,2,12) ,(6,2,3,20); SELECT * FROM crosstab(' SELECT usr::text ,question_id ,answer_id FROM qa ORDER BY 1,2') AS ct ( usr text ,q1 int ,q2 int ,q3 int);
Result:
usr | q1 | q2 | q3 -----+----+----+---- 1 | 1 | 9 | 15 2 | 2 | 12 | 20 (2 rows)
user is a reserved word . Do not use it as a column name! I renamed it to usr .
You need to install the tablefunc add-on module, which provides the crosstab() function. Please note that this operation is performed strictly for the database. In PostgreSQL 9.1, you can simply:
CREATE EXTENSION tablefunc;
For an older version, you must run the shell script specified in the contrib directory. On Debian for PostgreSQL 8.4, this will be:
psql mydb -f /usr/share/postgresql/8.4/contrib/tablefunc.sql