我具有一个季度按月平均产品销售量的汇总输出,如下所示:
汇总输出:
Product Month Sales
------------------------------
Product1 MAY 101.27
Product2 MAY 5.47
Product1 JUN 1481.19
Product2 JUN 84.95
ALL QTR 836.44
我需要以下格式的最终输出:
Product1 Product2 AverageSales
May 101.27 1481.19 (null)
Jun 5.47 84.95 (null)
Jul 0 0 (null)
ALL (null) (null) 836.44
我尝试对月份应用透视,但是由于月份名称是基于所选季度的动态值,因此我尝试对产品进行透视:
select * from (rollup output)
PIVOT MIN(Sales) FOR Product IN ('Product1' AS Product1_sales, 'Product2' AS Product2_sales, 'ALL' AS Average Sales');
我收到以下输出:
MONTH Product1_sales Product2_sales Average Sales
MAY 5.47 (null) (null)
MAY (null) 101.27 (null)
JUN 84.95 (null) (null)
JUN (null) 1481.19 (null)
Qtr (null) (null) 836.44
但是,我需要上述最终格式的数据。我该如何实现? 另外,如果没有该季度给定月份的数据,我想将其值显示为0(也以上述最终格式显示)。考虑到月份名称是动态的,我该如何实现?
编辑:我也可以使用产品进行透视,因为我不希望从动态透视中得到xml输出。
答案 0 :(得分:3)
我不确定为什么需要动态调整,因为月数不太可能更改。为什么不只是:
select product
, nvl(jan,0) as jan
, nvl(feb,0) as feb
, nvl(mar,0) as mar
, nvl(apr,0) as apr
, nvl(may,0) as may
, nvl(jun,0) as jun
, nvl(jul,0) as jul
, nvl(aug,0) as aug
, nvl(sep,0) as sep
, nvl(oct,0) as oct
, nvl(nov,0) as nov
, nvl(dec,0) as dec
from rollup_output
pivot (min(sales) for (month) in
( 'JAN' as jan, 'FEB' as feb, 'MAR' as mar, 'APR' as apr, 'MAY' as may, 'JUN' as jun
, 'JUL' as jul, 'AUG' as aug, 'SEP' as sep, 'OCT' as oct, 'NOV' as nov, 'DEC' as dec)
);