Question

Am using below crosstab query:

SELECT 
    * 
from crosstab('SELECT id,task_id, status_id FROM table ORDER BY 1,2')
     AS final_result(id character varying(50), task1 int,task2 int,task3 int,task4 int)

Result is below:

enter image description here

But I want the result like below:
in place of 1 I want result as 'name' and in place of 2 I want result as 'city'.

enter image description here

Was it helpful?

Solution

Like Akina commented, a CASE statement would do. That is, unless you have many more values to resolve, in which case you would typically join to a lookup table ...

SELECT * 
FROM   crosstab(
  $$SELECT id, task_id, CASE WHEN status_id = 1 THEN 'name' ELSE 'city' END
    FROM   tbl
    ORDER  BY 1,2$$
, $$SELECT unnest('{1, 2, 3, 4}'::text[])$$  -- suggestion, see below
   ) AS final_result(id text, task1 text, task2 text, task3 text, task4 text);

Using dollar-quoting to avoid confusion with double single-quotes.

And you might want to use the safe 2-parameter form for multiple task values where any can be missing or added. Provide actual task_id values for the suggested addition.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top