【求助】在一张表中,如何获取条件是同一个字段的不同维度的SUM总数?
大侠们。求助啊!!!
我有当前如下SQL:select sum(b.order_amount) as eqOrder,sum(c.order_amount) as eqOrderGSM
from
(select contract_no from opm_contract where project_no = '5522970' and period_id = '201308') a
left join opm_order b on a.contract_no = b.contract_no and b.period_id = '201308' and b.order_type='2'
left join opm_order c on a.contract_no = c.contract_no and c.period_id = '201308' and c.order_type='3'
我需要取order_type分别为'2','3'的order_amount的总数。
由于有很多这样的条件,所以导致需要左联很多次同一张表opm_order 。
问:怎么样写才能少连接同一张表opm_order呢 ?
------解决方案--------------------你的sum全部来自order表对吗,不需要使用如此多的左连接。
SELECT a.contract_no,
SUM(CASE WHEN b.period_id = '201308' and b.order_type='2' THEN b.order_amount END),
SUM(CASE WHEN b.period_id = '201308' and b.order_type='2' THENb.order_amount END)
FROM opm_contract a, opm_order b
WHERE a.contract_no = b.contract_no(+) GROUP BY a.contract_no;
------解决方案--------------------
select sum(decode(order_type,'2',order_amount,0)) eqOrder,
sum(decode(order_type,'3',order_amount,0)) eqOrderGSM
from opm_contract a left join opm_order b on a.contract_no = b.contract_no
where a.project_no = '5522970' and a.period_id = '201308'