Oracle行转列,列转行
时间: 2023-11-07 16:03:11 浏览: 128
在Oracle中,可以使用PIVOT和UNPIVOT操作实现行转列和列转行。
1. 行转列(PIVOT)
假设有如下表格:
```
CREATE TABLE sales (
salesperson VARCHAR2(20),
product VARCHAR2(20),
sales_date DATE,
amount NUMBER
);
INSERT INTO sales VALUES ('John', 'Product1', '01-Jan-2021', 100);
INSERT INTO sales VALUES ('John', 'Product2', '02-Jan-2021', 200);
INSERT INTO sales VALUES ('John', 'Product3', '03-Jan-2021', 300);
INSERT INTO sales VALUES ('Jane', 'Product1', '01-Jan-2021', 150);
INSERT INTO sales VALUES ('Jane', 'Product2', '02-Jan-2021', 250);
INSERT INTO sales VALUES ('Jane', 'Product3', '03-Jan-2021', 350);
```
如果想要将每个销售人员的销售额按照日期进行汇总,可以使用PIVOT操作:
```
SELECT *
FROM (
SELECT salesperson, sales_date, amount
FROM sales
)
PIVOT (
SUM(amount)
FOR sales_date IN ('01-Jan-2021', '02-Jan-2021', '03-Jan-2021')
);
```
输出结果为:
```
SALESPERSON '01-JAN-21' '02-JAN-21' '03-JAN-21'
----------- ---------- ---------- ----------
Jane 150 250 350
John 100 200 300
```
2. 列转行(UNPIVOT)
假设有如下表格:
```
CREATE TABLE sales (
salesperson VARCHAR2(20),
product1 NUMBER,
product2 NUMBER,
product3 NUMBER
);
INSERT INTO sales VALUES ('John', 100, 200, 300);
INSERT INTO sales VALUES ('Jane', 150, 250, 350);
```
如果想要将每个销售人员的销售额按照产品进行汇总,可以使用UNPIVOT操作:
```
SELECT salesperson, product, amount
FROM (
SELECT salesperson, product1, product2, product3
FROM sales
)
UNPIVOT (
amount FOR product IN (product1, product2, product3)
);
```
输出结果为:
```
SALESPERSON PRODUCT AMOUNT
----------- ------- ----------
John PRODUCT1 100
John PRODUCT2 200
John PRODUCT3 300
Jane PRODUCT1 150
Jane PRODUCT2 250
Jane PRODUCT3 350
```
阅读全文