简体   繁体   English

在Oracle 11g中使用数据透视表将行转换为列

[英]Convert rows into columns using pivot in oracle 11g

i want to convert rows into columns using PIVOT function. 我想使用PIVOT函数将行转换为列。

Example is below 示例如下

Table

EMP No   EMP Name
-------  --------
1         ABC
2         PQR

Output should be 输出应为

Col1         Col2
----         ----
Emp No         1
Emp Name       ABC
EMP No          2
Emp Name       PQR

I am ok with loop and all however we should have used PIVOT, have serached google however has not got anything matching. 我对循环没问题,但是所有我们都应该使用PIVOT,但是已经搜索过google,但是没有任何匹配项。

Please suggest and send some sample code. 请提出建议并发送一些示例代码。

Actually for you requirement, you need unpivot , not pivot . 其实你的要求,你需要unpivot ,没有pivot But for that, datatype of both columns should be same, character in this case 但是为此,两列的数据类型应该相同,在这种情况下为字符

with tab(emp_no, emp_name) as (
select '1' ,'abc' from dual union all
select '2' ,'PQR' from dual)
----
--End of Data Perparation
----
select * 
  from tab
unpivot (col2 for col1 in ( emp_no as 'EMP No', emp_name as 'Emp Name'));

Output 产量

|     COL1 | COL2 |
|----------|------|
|   EMP No |    1 |
| Emp Name |  abc |
|   EMP No |    2 |
| Emp Name |  PQR |

I'm not sure if this can be done using PIVOT. 我不确定是否可以使用PIVOT完成此操作。 You can select the columns separately and UNION them. 您可以分别选择列,并对其进行UNION。

select 'Emp No' col1, emp_no col2 from tab
union all
select 'Emp Name', emp_name from tab;

Note that, both the columns should be of same datatype. 请注意,两列都应具有相同的数据类型。 Else you need to cast/convert one of them. 否则,您需要转换/转换其中之一。

Also, the result may not be in the order you want. 另外,结果可能与您想要的顺序不符。 You need to sepecify the order by clause explicitly. 您需要明确区分order by子句。

select col1, col2 from(
    select 'Emp No' col1, emp_no col2, emp_no from tab
    union all
    select 'Emp Name', emp_name, emp_no from tab
    )
order by emp_no, case col1 when 'Emp No' then 1 else 2 end;

sqlfidle . sqlfidle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM