2

I have a table like this:

gid | cat1 | cat2 | some_value
-------------------------------
 1  |  A   | 100  |    I 
 2  |  B   | 200  |    II
 3  |  C   | 300  |    III
 4  |  D   | 400  |    IV

I would like to convert this table into something like this, i.e. convert a column value into a row value:

gid | category | value | some_value
-----------------------------------
 1  |   cat1   |   A   |     I
 1  |   cat2   |  100  |     I
 2  |   cat1   |   B   |     II
 2  |   cat2   |  200  |     II
... |   ...    |  ...  |     ...

Is this possible in Postgresql?

1 Answer 1

2

Use Union:

Select gid, 'cat1' as category, cat1 as value, some_value from t
union all
Select gid, 'cat2' as category, cast(cat2 as varchar(100)) as value, some_value from t
order by gid

here is a fiddle for it.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much! However, I get column "gid" does not exist for the first line. Any ideas?
do you have column gid in your table? did you changed table name from t to your actual table name?
Yes and yes - I actually built the table from my example. If I add from t in the first row it works, but I get UNION types character varying and integer cannot be matched in line 3
Oh, the cast should be for cat2, I changed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.