I have a PostgreSQL function (or table) which gives me the following output:
Sl.no username Designation salary etc..
1 A XYZ 10000 ...
2 B RTS 50000 ...
3 C QWE 20000 ...
4 D HGD 34343 ...
Now I want the Output as below:
Sl.no 1 2 3 4 ...
Username A B C D ...
Designation XYZ RTS QWE HGD ...
Salary 10000 50000 20000 34343 ...
How to do this?
Basing my answer on a table of the form:
Each row results in a new column to return. With a dynamic return type like this, it’s hardly possible to make this completely dynamic with a single call to the database. Demonstrating solutions with two steps:
Generally, this is limited by the maximum number of columns a table can hold. So not an option for tables with more than 1600 rows (or fewer). Details:
Postgres 9.4+
Dynamic solution with
crosstab()Use the first one if you can. Beats the rest.
Operating with
attnuminstead of actual column names. Simpler and faster. Join the result topg_attributeonce more or integrate column names like in the pg 9.3 example.Generates a query of the form:
This uses a whole range of advanced features. Just too much to explain.
Simple solution with
unnest()One
unnest()can now take multiple arrays to unnest in parallel.Result:
db<>fiddle here
Old sqlfiddle
Postgres 9.3 or older
Dynamic solution with
crosstab()Could be wrapped into a function with a single parameter …
Generates a query of the form:
Produces the desired result:
Simple solution with
unnest()Generates a query of the form:
Same result.