oracle 取消透视查询时卡住

0yycz8jy  于 2023-03-01  发布在  Oracle
关注(0)|答案(1)|浏览(104)

我必须取消透视此表
我试过这个

select * from unpivot2
unpivot (
( legendary,count)
  for type1 in ('Dragon', 'Psychic' , 'Fire')
) s;
ajsxfq5m

ajsxfq5m1#

如果很难理解PIVOTUNPIVOT运算符,只需使用UNIONGROUP BY来实现相同的操作。
创建原始透视表

CREATE TABLE pivot
(
    legendary   nvarchar(10),
    dragon      int,
    psychic     int,
    fire        int
);

插入记录

INSERT INTO pivot values
('false',20,43,47),
('true',12,14,15);

原始表格输出

SELECT * FROM pivot;

使用UNION运算符创建取消透视表。

CREATE TABLE unpivot AS
SELECT
    legendary,
    'dragon'    AS type1,
    dragon      AS value
FROM
    pivot
UNION
SELECT
    legendary,
    'psychic'   AS type1,
    psychic     AS value
FROM
    pivot
UNION
SELECT
    legendary,
    'fire'      AS type1,
    fire        AS value
FROM
    pivot
ORDER BY 
    type1;

查询反透视输出

SELECT
    *
 FROM
    unpivot;

使用UNIONGROUP BY运算符反向透视。

CREATE TABLE pivot AS
SELECT
    legendary,
    MAX(dragon)         AS  dragon,
    MAX(psychic)        AS  psychic,
    MAX(fire)           AS  value
FROM
(   
    SELECT
        legendary,
        value       AS      dragon,
        NULL        AS      psychic,
        NULL        AS      fire
    FROM
        unpivot
    WHERE
        type1='dragon'
    UNION
    SELECT
        legendary,
        NULL        AS      dragon,
        value       AS      psychic,
        NULL        AS      fire
    FROM
        unpivot
    WHERE
        type1='psychic'
    UNION
        SELECT
        legendary,
        NULL        AS      dragon,
        NULL        AS      psychic,
        value       AS      fire
    FROM
        unpivot
    WHERE
        type1='fire'
  
)set_union
GROUP BY legendary;

查询透视输出

SELECT * FROM pivot;

输出

希望这有帮助:)

相关问题