一.你需要準備?
- Oracle 11g+
目前該語法使用Oracle11g+版本,首先請覈實你的數據庫版本是否支持該語法;
select * from v$version;
二.基本介紹
SELECT 語句pivot_clause允許您編寫交叉表位查詢,將行旋轉到列中,在旋轉過程中聚合數據。透視是數據倉庫中的一項關鍵技術。在其中,您將多行輸入轉換爲數據倉庫中更少且通常更寬的行。透視時,將針對數據透視列值列表中的每個項應用聚合運算符。透視列不能包含任意表達式。如果需要在表達式上透視,則應在 PIVOT 操作之前將表達式別名化爲視圖中的表達式。
2.1基本語法
SELECT ....
FROM <table-expr>
PIVOT
(
aggregate-function(<column>)
FOR <pivot-column> IN (<value1>, <value2>,..., <valuen>)
) AS <alias>
WHERE .....
三.測試數據準備
3.1 創建表
create table sales
(
product VARCHAR2(32) not null,
country VARCHAR2(10),
channel VARCHAR2(100),
quarter CHAR(2),
amount_sold VARCHAR2(32),
quantity_sold varchar2(32)
);
3.2 插入數據
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('牛肉麪','中國','3','01','7','100');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('牛肉麪','中國','3','02','7','150');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('牛肉麪','中國','4','02','7','200');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('牛肉麪','中國','5','03','7','300');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('牛肉麪','中國','9','04','7','400');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('肯德基','美國','3','01','20','100');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('肯德基','美國','4','02','20','200');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('肯德基','美國','5','03','20','300');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('肯德基','美國','9','04','20','400');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('披薩','日本','3','01','15','100');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('披薩','日本','4','02','15','200');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('披薩','日本','5','03','15','300');
insert into sales (product,country,channel,quarter,amount_sold,quantity_sold)values('披薩','日本','9','04','15','400');
至此,我們創建了牛肉麪,肯德基,披薩三種產品在不同渠道,不同季度的銷售金額和銷售數量;
四.函數示例
4.1 單例透視
現在,我們要查詢某個產品在某個渠道銷售金額總和情況;
SELECT *
FROM (SELECT product, channel, amount_sold FROM sales) S
PIVOT(SUM(amount_sold)
FOR CHANNEL IN(3 AS 直營店,
4 AS 電商,
5 AS 自媒體,
9 AS 加盟店))
ORDER BY product;
4.2 多列透視
現在,我們要查詢某個產品在某個渠道和某個季度,銷售數量的總和;
SELECT *
FROM (SELECT product, channel, quarter, quantity_sold FROM sales)
PIVOT(SUM(quantity_sold)
FOR(channel, quarter) IN((5, '03') AS 自媒體三季度銷售量,
(4, '02') AS 電商二季度銷售量,
(3, '01') AS 直營店一季度銷售量,
(3, '02') AS 直營店二季度銷售量,
(9, '04') AS 加盟店四季度銷售量));
4.3 多個聚合
現在我們要查詢某個產品在某個渠道的銷售金額總和以及銷售數量總和;
SELECT *
FROM (SELECT product, channel, amount_sold, quantity_sold FROM sales)
PIVOT(SUM(amount_sold) AS sums, SUM(quantity_sold) AS sumq
FOR channel IN(5, 4, 3, 9))
ORDER BY product;
相關文章
1.Oracle 行轉列 pivot函數基本用法
2.Pivot 和 Unpivot