如何在以下方案中按类型汇总销售额

时间:2014-07-03 14:26:25

标签: sql oracle

在这种情况下,我有四个表:

  1. T_SALES包含

    等列
     CUST_KEY,
     ITEM_KEY,
     SALE_DATE,
     SALES_DLR
    
  2. T_ITEM包含

    等列
     ITEM_KEY
     ITEM_NUM
     ITEM_TYPE_ID
    
  3. T_ITM_MP_RLT包含

    等列
     ITEM_KEY
     MKT_PROG_KEY
    
  4. T_MKT_PROG包含

    等列
     MKT_PROG_KEY
     MKT_PROG_CDE
    
  5. 现在,我需要在sql中执行以下逻辑:

    对于属于项目Type = ‘RX’ and for the month of May 2012的所有项目  IF Marketing Program Code = 1 or 2 Aggregate Sales as Retail Program Sales ELSE IF Marketing Program Code = 4 or 7 Aggregate Sales as Hospital Program Sales ELSE Aggregate Sales as Acute Program Sales END END

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

select 
    case 
    when mkt_prog_cde in (1,2) then 'Retail Program Sales' 
    when mkt_prog_cde in (4,7) then 'Hospital Program Sales' 
    else 'Acute Program Sales'
    end as SalesType,
    sum(sales_dlr) as SalesTotal
from t_sales inner join t_item on t_item.item_key = t_sales.item_key
inner join t_itm_mp_rlt on t_itm_mp_rlt = t_item.item_key
inner join t_mkt_prog on t_mkt_prog.mkt_prog_key = t_itm_mp_rlt.mkt_prog_key
where t_item.item_type_id = X -- you need to add the join or lookup for item_type='RX' here
group by 
    case 
    when mkt_prog_cde in (1,2) then 'Retail Program Sales' 
    when mkt_prog_cde in (4,7) then 'Hospital Program Sales' 
    else 'Acute Program Sales'
    end

答案 1 :(得分:0)

我认为ITEM_KEYT_ITEM中的PK和其他地方的FK,而MKT_PROG_KEYT_MKT_PROG的PK和其他地方的FK:

select I.ITEM_KEY, I.ITEM_NUM, I.ITEM_TYPE_ID, M.MKT_PROG_CDE,
       sum(S.SALES_DLR) SALES_AMOUNT,
       case when M.MKT_PROG_CDE in (1, 2) then 'Retail Program Sales'
            when M.MKT_PROG_CDE in (4, 7) then 'Hospital Program Sales'
            else 'Acute Program Sales'
            end label
from T_SALES S, T_ITEM I, T_ITM_MP_RLT R, T_MKT_PROG P
where trunc(S.SALE_DATE, 'MON') = '01 May 2012'
  and I.ITEM_KEY = S.ITEM_KEY
  and I.ITEM_TYPE_ID = 'RX'
  and R.ITEM_KEY = I.ITEM_KEY
  and P.MKT_PROG_KEY = R.MKT_PROG_KEY
group by I.ITEM_KEY, I.ITEM_NUM, I.ITEM_TYPE_ID, M.MKT_PROG_CDE