I have a query that should pivot a table with large number of values in a certain column that should be transformed into the column names of the pivoted table, i.e.,
SELECT *
FROM crosstab(
$$SELECT user_id, item_id, rating
FROM tbl
ORDER BY 1,2$$
) AS ct ("user_id" varchar(50), "select distinct item_id from tbl ORDER BY 1" varchar(50)[]);
This attempt results in an error: return and sql tuple descriptions are incompatible. I am sure that the type of user_id and item_id columns is varchar(50). However, I am not sure what should be the type of the second argument that is a query.
This query has been generated following the example given in the first answer at PostgreSQL Crosstab Query. It mentions that the second argument can be a query.
Any help to fix this problem would be great. Thank you.
Edit:
For the purpose of providing MNE, the table tbl can be created by:
CREATE TABLE tbl (
user_id varchar(50)
, item_id varchar(50)
, rating integer
);
INSERT INTO tbl VALUES
('A', 'item_0', 1), ('A', 'item_3', 2)
, ('B', 'item_1', 4), ('B', 'item_2', 5)
, ('C', 'item_0', 3);
The desired outcome is:
user_id item_0 item_1 item_2 item_3
A 1 2
B 4 5
C 3
Note that, in the actual scenario, the number of distinct values in the item_id column of table tbl is about 2000.