Oracle数据库11G版本中的 PIVOT 和 UNPIVOT 的操作符

原文链接:https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1

本文介绍了如何使用新的PIVOT和UNPIVOT操作符在11g中,以及如何针对相同的问题给出11g之前的解决方案。

PIVOT

PIVOT操作符以单独的行获取数据,聚合数据并将其转换为列。要查看PIVOTca操作符的动作,我们需要创建一个测试表。

CREATE TABLE pivot_test (
  id            NUMBER,
  customer_id   NUMBER,
  product_code  VARCHAR2(5),
  quantity      NUMBER
);

INSERT INTO pivot_test VALUES (1, 1, 'A', 10);
INSERT INTO pivot_test VALUES (2, 1, 'B', 20);
INSERT INTO pivot_test VALUES (3, 1, 'C', 30);
INSERT INTO pivot_test VALUES (4, 2, 'A', 40);
INSERT INTO pivot_test VALUES (5, 2, 'C', 50);
INSERT INTO pivot_test VALUES (6, 3, 'A', 60);
INSERT INTO pivot_test VALUES (7, 3, 'B', 70);
INSERT INTO pivot_test VALUES (8, 3, 'C', 80);
INSERT INTO pivot_test VALUES (9, 3, 'D', 90);
INSERT INTO pivot_test VALUES (10, 4, 'A', 100);
COMMIT;

所以我们的测试数据就这样开始了。

SELECT * FROM pivot_test;

        ID CUSTOMER_ID PRODU   QUANTITY
---------- ----------- ----- ----------
         1           1 A             10
         2           1 B             20
         3           1 C             30
         4           2 A             40
         5           2 C             50
         6           3 A             60
         7           3 B             70
         8           3 C             80
         9           3 D             90
        10           4 A            100

10 rows selected.

你可能感兴趣的:(PLSQL基础知识)