如何垂直显示记录?

时间:2016-05-16 09:49:22

标签: sql postgresql

我有这张表employee

emp_id  |  emp_name  |   emp_age      |  emp_add
-----------------------------------------------------
 1      |    Bob     |    12          |     China
 2      |    George  |    14          |     Japan
 3      |    Leo     |    20          |     USA

然后我想创建一个选择查询(或者可能是存储过程),它将像这样显示上面的表

     COL1   |   COL2    |   COL3     |  COL4
-----------------------------------------------------
 emp_id     |    1      |    2       |     3
 emp_name   |    Bob    |    George  |     Leo     
 emp_age    |    12     |    14      |     20
 emp_add    |    China  |    Japan   |     USA

这可能吗?我正在使用postgreSQL:)

如果有可能,我希望它是灵活的(存储过程),以便我可以在另一个表上使用它。 谢谢:))

1 个答案:

答案 0 :(得分:1)

使用union和case来根据您的情况获得所需的透视结果,如下所示

select 'emp_id' as col1, min(emp_id) col2,(select emp_id from employees where emp_id =2) 
                       as col3,max(emp_id) as col4
    from employees                       
    union all
    select 'emp_name' as col1,min(emp_name)as col2,
           (select emp_name from employees where emp_id =2 and emp_add ='Japan') as col3,
           (select emp_name from employees where emp_id =3 and emp_add ='USA') as col4
 from employees
   union all
            select 'emp_age' as col1,min(emp_age) as col2,
                                (select emp_age from employees where emp_id =2 and emp_age =14) as col3,
                                max(emp_age) as col4
            from employees
            union all
            select 'emp_add' as col1,case  when emp_add ='china' Then min(emp_add) end as col2,
                                (select emp_add from employees where emp_age=14 )as col3,
                                (select emp_add from employees where emp_age=20 )as col4 
            from employees