在这种情况下,我有四个表:
T_SALES
包含
CUST_KEY,
ITEM_KEY,
SALE_DATE,
SALES_DLR
T_ITEM
包含
ITEM_KEY
ITEM_NUM
ITEM_TYPE_ID
T_ITM_MP_RLT
包含
ITEM_KEY
MKT_PROG_KEY
T_MKT_PROG
包含
MKT_PROG_KEY
MKT_PROG_CDE
现在,我需要在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
答案 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_KEY
是T_ITEM
中的PK和其他地方的FK,而MKT_PROG_KEY
是T_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