I've got a PostgreSQL table which I have to transpose.
The original data looks like:
user_id role_id assigned
P0001 SA t
P0001 Guest t
P0002 SA f
P0002 Guest t
After transposing, it should look like as follows:
user_id SA Guest
P0001 t t
P0002 f t
The following is what I used to generate the transposed table:
SELECT user_id,
CAST(CAST(CASE role_id WHEN 'SA' THEN 1 ELSE 0 END) AS int) AS boolean) AS "SA",
CAST(CAST((CASE role_id WHEN 'Guest' THEN 1 ELSE 0 END) AS int) AS boolean) AS "Guest"
FROM user_to_roles GROUP BY user_id
But it looks ugly. Is there a way to write an custom aggregation function doing nothing but returning the original value. So the above statement can be re-written as:
SELECT user_id,
Do_Nothing(CASE role_id WHEN 'SA' THEN true ELSE false END) AS "SA",
Do_Nothing(CASE role_id WHEN 'Guest' THEN true ELSE false END) AS "Guest"
FROM user_to_roles GROUP BY user_id
Edit:
Actually, I need a dynamic generated columns and implemented it using the cursor by the help of this article. And I looked into the documentation and write a custom aggregation like this:
CREATE AGGREGATE do_nothing(anyelement) (
SFUNC=donothing,
STYPE=anyelement,
INITCOND=''
);
CREATE OR REPLACE FUNCTION donothing(anyelement var)
RETURNS anyelement AS
$BODY$
RETURN var;
$BODY$
LANGUAGE sql IMMUTABLE
COST 100;
Since I want to make it generic, anyelment
was used here.
But the above code doesn't work at all.