选择列作为行

时间:2013-07-24 11:20:34

标签: sql oracle pivot

select * from emp14;

输出:

EMPLOYEE_ID FIRST_NAME  LAST_NAME   EMAIL   
100          Steven            King         SKING   

我想按列显示输出,如下所示:

EMPLOYEE_ID  100
FIRST_NAME   Steven
LAST_NAME    King
EMAIL        SKING

4 个答案:

答案 0 :(得分:3)

试试这个

SELECT col, val
FROM
(
  SELECT to_char(EMPLOYEE_ID) AS EMPLOYEE_ID,FIRST_NAME,LAST_NAME, EMAIL FROM emp14
)t 
UNPIVOT INCLUDE NULLS
( 
  VAL FOR col IN (EMPLOYEE_ID,FIRST_NAME,LAST_NAME, EMAIL)
);

SQL FIDDLE DEMO

答案 1 :(得分:0)

您似乎希望每列显示在单独的行中。运行SELECT语句的结果将以用于运行查询的特定工具选择的任何方式显示。如果你真的希望每一列显示在一个单独的行上,你可以使用一点PL / SQL:

BEGIN
  FOR aRow IN (SELECT * FROM EMP14) LOOP
    DBMS_OUTPUT.PUT_LINE('EMPLOYEE_ID  ' || aRow.EMPLOYEE_ID);
    DBMS_OUTPUT.PUT_LINE('FIRST_NAME   ' || aRow.FIRST_NAME);
    DBMS_OUTPUT.PUT_LINE('LAST_NAME    ' || aRow.LAST_NAME);
    DBMS_OUTPUT.PUT_LINE('EMAIL        ' || aRow.EMAIL);
  END LOOP;
END;

分享并享受。

答案 2 :(得分:0)

另一种方法:

-- this type is going to contain value's name and the value itself
SQL> create type t_data is object(
  2    col1 varchar2(31),
  3    col2 varchar2(31)
  4  );
  5  /

Type created


SQL> create type t_table is table of t_data;
  2  /

Type created

之后,可以通过以下方式构建查询:

-- sample of data from the question + some extra  data 
-- just for the sake of demonstration.
SQL> with t1(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL) as
  2  (  select 100, 'Steven', 'King', 'SKING' from dual union all
  3     select 101, 'Steven1', 'King1', 'SKING1' from dual
  4   )
  5  select col1
  6       , col2
  7    from t1 t
  8    cross join table(
  9                     t_table( t_data('Employee_id', t.employee_id)
 10                             , t_data('First_name', t.first_name)
 11                             , t_data('Last_Name' , t.last_name)
 12                             , t_data('e-mail'    , t.email)
 13                             )
 14                     )
 15  ;

结果:

COL1                            COL2
------------------------------- -------------------------------
Employee_id                     100
First_name                      Steven
Last_Name                       King
e-mail                          SKING
Employee_id                     101
First_name                      Steven1
Last_Name                       King1
e-mail                          SKING1

8 rows selected

答案 3 :(得分:-1)

select concat('EMPLOYEE_ID ', EMPLOYEE_ID) as EMPLOYEE_ID,
       concat( 'FIRST_NAME ' ,   FIRST_NAME) as FIRST_NAME,
       concat('LAST_NAME ' ,  LAST_NAME) as LAST_NAME,
       concat('EMAIL ' , EMAIL)  as EMAIL 
from email