1

I need to transpose columns to rows in postgreSQL. Below is the requirement. Any help is appreciated.

Source table/data :

id   class-1-male class-1-female class-2-male  class-2-female class-3-male  class-3-female<br> 
1      1                1                11              7          0                9<br> 
2      11              31                6              7          40               92<br> 
3      15              31                8              37         30               91<br> 
4      11              13                50             17         10               19<br> 

I want data in below format:

id   class-type male female<br> 
1     class-1    1     1<br> 
2     class-1    11    31<br> 
3     class-1    15    31<br> 
4     class-1    11    13<br> 
1     class-2    11    7<br> 
2     class-2    6     7<br> 
3     class-2    8     37<br> 
4     class-2    50    17<br> 
1     class-3    0     9<br> 
2     class-3    40    92<br> 
3     class-3    30    91<br> 
4     class-3    10    19<br>

THanks Jitendra

1 Answer 1

1

A union is probably what you're looking for:

select id,
       'class1'::text as "class-type",
       "class-1-male" as male,
       "class-1-female" as female
from data
union all
select id,
       'class2'::text as "class-type",
       "class-2-male" as male,
       "class-2-female" as female
from data
union all
…
Sign up to request clarification or add additional context in comments.

1 Comment

@Lotus92: that one is the other way around. Also, avoid url shorteners on this site.

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.