Oracle 从 3 列创建一个 Pivot table

Oracle create a Pivot table from 3 columns

我正在尝试创建一个类似于 excel 的枢轴 table,其中包含 3 列信息、订单类型、产品代码以及该订单产生的收入。

我已经设法获得了同一产品的每个订单产生的收入,按订单 tpye 订购。

select ORDER_TYPE, PRODUCT_CODE, sum(INCOME)
from Logistics
group by ORDER_TYPE, PRODUCT_CODE
order by ORDER_TYPE;

来自输出查询的片段:

ORDER_TYPE, PRODUCT_CODE, sum(INCOME):
EB  ZOL 432919
EB  ITA 24832674
EB  ELM 2095035
EB  FRI 1464608
EB  ESZ 0
EB  GON 1707758
EB  PVE 23130
EK  FRI 10560880
EK  ITA 30207062
EK  PVE 1625576
EK  ESZ 0
EK  ZOL 1467432
EK  GON 11208618
EK  ELM 14159542
ER  PVE -12449
ER  ITA -3808222
ER  ELM -236587
ER  ZOL -17394
ER  GON -16758710
ER  FRI -102844
ER  ESZ -104169
ER      33142
ES  ZOL 13883
ES  FRI -12860
ES  ELM -107442
ES  SZO -46800
ES  PVE 0
ES  GON 0
ES  ITA -61427
E1  ELM 29195518

如您所见,由于产品不同,现在每种订单类型都有几行。

我如何修改此查询以获得一个数据透视表 table,其中包含每种订单类型的列和产品代码的行,因此我只有一列用于订单类型而不是行?

例如:

    EB    EK    ES    ER
ZOL income datas
ITA for every
ELM cell
FRI 
ESZ 
GON 
PVE 
FRI 

用例

select PRODUCT_CODE,(case when ORDER_TYPE='EB' then s_income end) as EB,
sum(case when ORDER_TYPE='Ek' then income else 0 end) as EK,
sum(case when ORDER_TYPE='ES' then income else 0  end) as ES,
sum(case when ORDER_TYPE='ER' then income else 0  end) as ER
from Logistics group by PRODUCT_CODE

使用 Oracle SQL 中定义的数据透视 table 功能 https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1

您标记了 Oracle18c,因此这应该适用于您的版本。我在 11g 上测试过这个。

SELECT *
FROM (
  SELECT product_code, order_type, income
  FROM Logistics
)
PIVOT (
  sum(income)  
  for order_type
  IN ('EB' AS EB, 'ER' AS ER, 'ES' AS ES, 'EK' AS EK)
);

这确实需要在执行之前填写 IN 列表的集合。还有另一种语法允许子 select 但它是 returns XML。如果您尝试将 PIVOT XML 替换为 PIVOT,则会出现错误。

WITH orderTypes AS
(
    select 'EB' as order_type from dual union all
    select 'ER' as order_type from dual union all
    select 'ES' as order_type from dual union all
    select 'EK' as order_type from dual union all 
    select 'AA' as order_type from dual union all
    select 'AB' as order_type from dual union all
    select 'AC' as order_type from dual union all
    select 'AD' as order_type from dual union all
    select 'AE' as order_type from dual        

)
SELECT *
FROM (
  SELECT l.product_code, l.order_type, l.income
  FROM Logistics l
)
PIVOT XML  (
  sum(income) AS orderSum
  for order_type 
  IN ( select order_type from orderTypes)
);