您想要的是此处所述的“枢轴”:https://www.techonthenet.com/oracle/pivot.php。
这是一个可能适用于您的示例的查询:
create table TableA(
Year int,
Shop varchar2(100),
Sales int
);
delete from TableA;
insert into TableA(Year,Shop,Sales) values(2015,'Shop-A',100);
insert into TableA(Year,Shop,Sales) values(2015,'Shop-B',200);
insert into TableA(Year,Shop,Sales) values(2015,'Shop-C',300);
insert into TableA(Year,Shop,Sales) values(2016,'Shop-A',100);
insert into TableA(Year,Shop,Sales) values(2016,'Shop-B',100);
insert into TableA(Year,Shop,Sales) values(2016,'Shop-C',100);
insert into TableA(Year,Shop,Sales) values(2017,'Shop-A',100);
/* Show the table as is before pivot*/
select *
from TableA;
/* The pivoted data. Note that liberties were taken to correct the 2016 - ShopA sales data. */
select *
from
(
select
year,
sales,
shop
from TableA
)
pivot
(
max(sales)
for shop in('Shop-A','Shop-B','Shop-C')
)
order by year;
我在SQL Fiddle 中设置了上面的示例,它返回了预期的结果。
请注意,PIVOT 子句的一个缺点是 FOR 子句中列出的值在查询中是静态的。解决此问题的唯一方法是使用动态 SQL 构建 PIVOT 查询,以便将列动态添加到查询中并相应地执行构造的查询字符串。