Oracle从3列创建数据透视表

时间:2019-03-31 18:31:47

标签: sql oracle oracle18c

我正在尝试创建一个类似excel的数据透视表,其中包含3列信息,订单号,产品代码以及从该订单中产生的收入。

我已经设法从同一产品(按订单tpye排序)获得每个订单的收入。

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

输出查询中的片段:

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

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

如何修改此查询以获取数据透视表,该数据透视表具有每种订单类型的列和产品代码的行,因此订单类型只有一列而不是行?

例如:

{{1}}

3 个答案:

答案 0 :(得分:1)

用例何时

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您已标记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列表的设置。还有另一种语法允许子选择,但它返回XML。如果尝试用PIVOT替换PIVOT XML,则会出现错误。

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)
);