oracle sql - 如何使用维度列分组获得全年(12个月)的总和

时间:2017-01-27 19:03:37

标签: sql oracle

enter code here大家好,  我有一个场景,我需要找到比较2个表的方差  第一个表是Z_F_DDEPL_ALLRPTG,第二个表是F_DDEPL_ALLRPTG   表羞耻列名称和相同列数。  有些列中有数量(从3月到2月的年份),所以我需要将这些数量的列和组合在左侧的维度列上进行比较,然后比较两个表格并查看是否存在任何金额差异。 这是我创建的sql,但由于某种原因它没有给我输出我需要请帮助

select distinct 
YEAR_CD,
SCENARIO_CD,
MANAGEMENT_CD,
PRODUCT_CD,
OPCO_CD,
ACCOUNT_CD,
sum(BEGBALANCE_QTY) as BEGBALANCE_QTY ,
sum(MAR_QTY) as MAR_QTY,
sum(APR_QTY) as APR_QTY,
sum(MAY_QTY) as MAY_QTY,
sum(JUN_QTY) as JUN_QTY,
sum(JUL_QTY) as JUL_QTY,
sum(AUG_QTY) as AUG_QTY,
sum(SEP_QTY) as SEP_QTY,
sum(OCT_QTY) as OCT_QTY,
sum(NOV_QTY) as NOV_QTY,
sum(DEC_QTY) as DEC_QTY,
sum(JAN_QTY) as JAN_QTY,
sum(FEB_QTY) as FEB_QTY
from LND_FPAR.Z_F_DDEPL_ALLRPTG a 
 join LND_FPAR.F_DDEPL_ALLRPTG b
  on a.YEAR_CD=b.YEAR_CD
and a.SCENARIO_CD= b.SCENARIO_CD
and a.MANAGEMENT_CD=b.MANAGEMENT_CD
and a.PRODUCT_CD=b.PRODUCT_CD
 and a.OPCO_CD=b.OPCO_CD
 and a.ACCOUNT_CD=b.ACCOUNT_CD
--where opco_cd='OCO101'
 group by  
YEAR_CD,
SCENARIO_CD,
MANAGEMENT_CD,
PRODUCT_CD,
OPCO_CD,
ACCOUNT_CD
order by year_cd;

1 个答案:

答案 0 :(得分:0)

您可以使用union all和条件聚合进行并排比较:

select YEAR_CD, SCENARIO_CD, MANAGEMENT_CD, PRODUCT_CD, OPCO_CD, ACCOUNT_CD,
       sum(case when which = 'a' then MAR_QTY end) as MAR_QTY_a,
       sum(case when which = 'b' then MAR_QTY end) as MAR_QTY_b,
       . . .
from ((select 'a' as which, YEAR_CD, SCENARIO_CD, MANAGEMENT_CD, PRODUCT_CD, OPCO_CD, ACCOUNT_CD,
              MAR_QTY, . . .
       from LND_FPAR.Z_F_DDEPL_ALLRPTG
      ) union all
      (select 'b' as which, YEAR_CD, SCENARIO_CD, MANAGEMENT_CD, PRODUCT_CD, OPCO_CD, ACCOUNT_CD,
              MAR_QTY, . . .
       from LND_FPAR.F_DDEPL_ALLRPTG
      )
     ) ab
group by YEAR_CD, SCENARIO_CD, MANAGEMENT_CD, PRODUCT_CD, OPCO_CD, ACCOUNT_CD;

(使用您要比较的列填写. . .。)

我不知道你想怎么做比较。