透视多列Oracle SQL

时间:2017-10-03 07:09:36

标签: sql oracle oracle11g pivot

我有一张名为“Books”的表

ID | lan_id | main_title  | part
---------------------------------
1  |  1     | Quick guide | 1
2  |  1     | Quick guide | 4
---------------------------------

我想要实现的目标是:

--------------------------------------------
ID         |   1            |   2
Lan_id     |   1            |   1
main_tile  |   Quick guide  |   Quick guide
part       |   1            |   4
--------------------------------------------

我想我需要一个支点,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

使用UNPIVOT然后PIVOT

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name ( ID, lan_id, main_title, part ) AS
SELECT 1, 1, 'Quick guide', 1 FROM DUAL UNION ALL
SELECT 2, 1, 'Quick guide', 4 FROM DUAL;

查询1

SELECT *
FROM   ( SELECT ROWNUM AS rn,
                TO_CHAR( id ) AS id,
                TO_CHAR( lan_id ) AS lan_id,
                main_title,
                TO_CHAR( part ) AS part
         FROM   table_name )
UNPIVOT ( value FOR key IN (
  id,
  lan_id,
  main_title,
  part
) )
PIVOT ( MAX( value ) FOR rn IN (
  1 AS "1",
  2 AS "2"
) )
ORDER BY key

<强> Results

|        KEY |           1 |           2 |
|------------|-------------|-------------|
|         ID |           1 |           2 |
|     LAN_ID |           1 |           1 |
| MAIN_TITLE | Quick guide | Quick guide |
|       PART |           1 |           4 |

答案 1 :(得分:0)

您可以按照以下方式同时使用UNPIVOTPIVOT

WITH Books (Id,
            lan_id,
            main_title,
            part)
     AS (SELECT 1, 1, 'Quick guide', 1 FROM DUAL
         UNION ALL
         SELECT 2, 1, 'Quick guide', 4 FROM DUAL)
SELECT *
  FROM (SELECT *
          FROM (SELECT TO_CHAR (id) id,
                       TO_CHAR (lan_id) lan_id,
                       main_title,
                       TO_CHAR (part) part,
                       TO_CHAR (ROWNUM) rn
                  FROM Books) UNPIVOT (columns
                              FOR header
                              IN (Id, lan_id, main_title, part))) PIVOT (MAX (
                                                                            columns)
                                                                     FOR rn
                                                                     IN (1 AS row1,
                                                                        2 AS row2));

<强>输出

Header             row1 row2
-----              ---- ----
ID                 1    2
LAN_ID             1    1
MAIN_TITLE  Quick guide Quick guide
PAIR               1    4