将列转置为行 - postgres

时间:2013-11-07 08:27:14

标签: postgresql

我需要将列转换为postgreSQL中的行。以下是要求。 任何帮助表示赞赏。

来源表/数据:

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> 

我想要以下格式的数据:

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>

感谢 Jitendra

1 个答案:

答案 0 :(得分:1)

联盟可能就是你要找的东西:

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
…