点击上方“蓉李纪”,关注订阅更多优质内容
后台回复"加群",加入技术交流群一起进步
在这里插入图片描述select * from v$version;
在这里插入图片描述
SELECT 语句pivot_clause允许您编写交叉表位查询,将行旋转到列中,在旋转过程中聚合数据。透视是数据仓库中的一项关键技术。在其中,您将多行输入转换为数据仓库中更少且通常更宽的行。透视时,将针对数据透视列值列表中的每个项应用聚合运算符。透视列不能包含任意表达式。如果需要在表达式上透视,则应在 PIVOT 操作之前将表达式别名化为视图中的表达式。
SELECT ....
FROM
PIVOT
(
aggregate-function()
FOR IN (, ,..., )
) AS
WHERE .....
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)
);
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');
至此,我们创建了牛肉面,肯德基,披萨三种产品在不同渠道,不同季度的销售金额和销售数量;
现在,我们要查询某个产品在某个渠道销售金额总和情况;
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;
现在,我们要查询某个产品在某个渠道和某个季度,销售数量的总和;
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 加盟店四季度销售量));
现在我们要查询某个产品在某个渠道的销售金额总和以及销售数量总和;
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函数基本用法: https://blog.csdn.net/huay_li/article/details/82914161
[2]Pivot 和 Unpivot: https://www.oracle.com/technetwork/cn/articles/11g-pivot-101924-zhs.html
点个在看支持我吧,转发就更好了